Showing posts with label for loop. Show all posts
Showing posts with label for loop. Show all posts

Thursday, 25 June 2015

For loop in C : Features I never heard of

We usually use for loop when there is a known number of iterations... Where the while loop is when number of iterations not known in advance.

For loop allow us to define Three expressions in its syntax.

1.Initialization
2.Testing condition
3.change or update

Initialization : It is done Just once,when the for loop just starts.
so it will done its job even though the condition is false in the first iteration.

Testing Condition : It is evaluated before each potential execution of loop
If the condition is true then statements in the loop are executed. If not the it will jump from the loop(the loop is terminated).

Change or Update : It is Evaluated at the end of each loop.

In its syntax it is having three Expressions Separated by Semicolon (;) every time i put a colon instead if semicolon which eventually gives me an syntax error.

For loop Must have Two semicolons even though there are no Expressions

for( ;  ;  )
{

}

is considered as infinite loop

initialization will run only once at the beginning of for loop even though the condition is false.

#include<stdio.h>
#include<conio.h>
int main(void)
{
int a = 6;

for(printf("a = %d \n",a);a<3;) // condition is false
{
printf("entered for loop\n");
}

printf("for loop is terminated\n");
getch();
return 0;
}

output :

Please note that condition is false at the first test But initialisation is executed.

Comma Operator :
Comma operator is useful when we wanted to Include more than One initialization or update expression in for loop.
#include<stdio.h>
#include<conio.h>
int main(void)
{
int i,j;

for(printf("i\tj\n"),i=0,j=0;i<3;i++,j++)
{
printf("%d\t%d\n",i,j);
}

printf("for loop is terminated");
getch();

return 0;

}//end of main

Output :

please note that we cant use colon operator in test condition.






Monday, 6 April 2015

Using Arrays and For loop

The following code demonstrates the simple use of Arrays Using for loop
In this code four Led's are On and Off Sequentially.


/*
Author : Kunchala Anil
demonstrating the use of Arrays using For loop
*/
int led[] = {8,9,10,11}; // initialize the 4 pins using array
void setup(){
Serial.begin(9600);
//for loop is used to set all pins to Outputs
for(int i=0;i<4;i++){
pinMode(led[i],OUTPUT);
Serial.print("pin\t");
Serial.print(i);
Serial.print("\t is set as Output")
Serial.println("");
}//end of for loop
}//end of setup() function

void loop(){
//for loop is used to On and Off Led's Sequentially
for(int j=0;j<4;j++){
digitalWrite(led[j],HIGH);
Serial.print("LED\t");
Serial.print(j);
Serial.print("\t is ON")
Serial.println("");
delay(1000);
digitalWrite(led[j],LOW);
Serial.print("LED\t");
Serial.print(j);
Serial.print("\t is OFF")
Serial.println("");

}//end of for loop
}//end of loop