C For loop and Nested for loop with Examples and Programs:
C For Loop and Syntax of C for loop:The for statement is the most commonly used looping statement. The statement includes initialization expression that specifies an initial value for an index and the condition expression determines whether the loop is continued or not and last iteration expression allows the index to be modified at the end of each pass.
Syntax of C for() loop:
for(initialization; condition; iteration)
{
//codes to be Executed//
//codes to be Executed//
}
C For loop program:
C For loop program:
#include <stdio.h>
int main()
{
int i;
for(i = 1; i<=10; i++)
{
printf("value of i = %d \n",i);
}
printf("Example of For Loop");
return 0;
}
C For loop Output:
value of i = 1
value of i = 2
value of i = 3
value of i = 4
value of i = 5
value of i = 6
value of i = 7
value of i = 8
value of i = 9
value of i = 10
Example of For Loop
Explanation of the above program:
- Variable of type int (integer) is declared.
- Now in for loop first it is initialized as 1.
- Now the condition is checked 1 is less than 10. So the value is printed.
- The loop continues until the value of “i” becomes “11” the condition (11<=10) is false so the control jumps out of for loop.
In the above, we explained using the Increment
operator. Using the Decrement operator we use for loop.
C For loop program using decrement Example:
C For loop program using decrement operator:
#include <stdio.h>
int main()
{
int i;
for(i = 4; i>=1; i--)
{
printf("value of i = %d \n",i);
}
printf("Example of For Loop");
return 0;
}
C For loop program using decrement example output:
value of i = 4
value of i = 3
value of i = 2
value of i = 1
Nested
for loops in C: Nested for loops allow loops to be nested.
That is one for loop present inside another for a loop.
Nested for loop in C Example:
Nested For loop in C program:
#include <stdio.h>
int main()
{
int i,j;
for(i = 0; i < 5; i++)
{
for(j = i; j < 5; j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Nested For loop in C Output:
*****
****
***
**
*