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.