Boost Your Programming Skills with For Loop in C

for loop in c is useful to execute group of statements as long as the condition is true. for loop is more suitable when the programmer knows how many times exactly the statements should be executed. It means for loop is suitable to execute statements a fixed number of times.

Syntax: for(expression1; expression2; expression3)
        {
          statements;
        }
Example: for(i=1;i<=10;i++)
        {
              printf("\n%d",i);
        }

Here, expression1 is called ‘initialization expression’ as it is used to initialize a variable (i=1). Expression1 is executed only once in the beginning of the loop. Expression2 is called ‘conditional expression’ as it represents a condition (i<=10).As long as condition is true,the statements inside the for loop will be executed.Expression 3 is called ‘modifying expression’ as it either increments or decrements the value of the variable (i++).

The for loop in the above example print numbers from 1 to 10 since the starting value of i is 1, the ending is 10 and each time i is incremented by 1.So, the i values will be 1, 2, 3, 4, 5, 6, 7, 8, 9, and 10. When the i value becomes 11, the condition i<=10 becomes false, so the for loop terminates and the i value 11 will not be displayed.

Program: for loop to display numbers upto 10.

#include<stdio.h>
void main()
{
  int i;
  for(i=1;i<=10;i++)
  printf("\n%d",i);
}

Output:

1
1
3
4
5
6
7
8
9
10

It is possible to write for loop without using any one expression ir any two expressions or all the three expressions.

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

Example: for loop in c without expression1.

int i=1;
for(; i<=10; i++)
{
  printf("\n%d",i);
}

Here, i value is declared outside the for loop and hence expression1 can be eliminated.

Example: for loop without expression1 and expression3.

int i=1;

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

Here, incrementing the i value can be done inside the for loop after displaying the value.

Example: for loop without all three expressions.

int i=1;

for(; ;)
{
  printf("\n%d",i);
         i++;
}

In this example, the expression2 which represents a condition, is not present. Since there is no condition, this loop does not know where to stop.So,it will continue execution for ever. Such a loop is called ‘Infinite loop’.
Infinte loop can be created using for, do while or while loops also.

Naveed Tawargeri
 

Hi, I'm Naveed Tawargeri, and I'm the owner and creator of this blog. I'm a Software Developer with a passion for Programming.