{ A destination to learn coding }

Iteration Statements

For Loop variations

C allows us to modify and create several variations of the for loop.

We can use 2 or more loop control variables

#include<stdio.h>
int main()
{
int i,j;

for(i=0, j=10; i<10; i++, j--)
{
  printf("%d + %d = %d\n",i,j,i+j);
}

printf("The value of i is %d",i);
return 0;
}

In the example above, i and j both are initialized, separated by a comma operator. In the increment expression, i is incremented and j is decremented.


Different Conditional expressions

As stated earlier, a condition can be anything. C also allows you to add complex conditions in the loops.

for(a=0; (a!=5)&&(a<10) ; a++)
{
  printf("Hello World\n");
}

Expressions are optional

Another interesting variation of for loop is, all the expressions need not be there.

In this code increment expression is missing
#include<stdio.h>
int main()
{
int i;
for(i=1; i!=0; )
{
  printf("Enter a value\n");
  scanf("%d",&i);
}

return 0;
}

Even the initialization part can be omitted by initializing the variable outside the loop.
See the example below.

#include<stdio.h>
int main()
{
int i;
for( ;i<10; )
{
printf("Hello World\n");
i++;
}
return 0;
}

The infinite loop

for(;;) statement;
The code below will print hello world for infinite number of times
for( ; ; )
	printf("Hello World\n");

There is no need of any expression for an infinite for loop.

Note:You can make infinite loop using any of the 3 loops

Try this
Printing table of any number
Display first 10 natural numbers
Find factorial of a number
Code to check for a prime number.
Fibonacci Series
You can even try printing patterns
C Codes