For loop in C Programming

For loop in C

  • for loop is useful to execute a 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 at the beginning of the loop. Expression2 is called ‘conditional expression’ as it represents a condition (i<=10).As long as the condition is true, the statements inside the 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 value is incremented by 1.So, i values will change as 1,2,3,4,5,6,7,8,9,10. When I value becomes 11, the condition I <=10 becomes false, so the for loop terminates and i value 11 will not be displayed.

Program: for loop to display numbers up to 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 a 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 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 for loop does not know where to stop. So, it will continue execution forever, such a loop is called ‘Infinite loop’.
  • An infinite loop can be created using for,do..while or while loops also.
naveed08st
 

Click Here to Leave a Comment Below 0 comments

Leave a Reply:

Select Language
Copy link
Powered by Social Snap