Nested For Loop:
In the previous tutorial of if-else, control statements we saw what nested if is. Nested for loop refers to the process of having one loop inside another loop. We can have multiple loops inside one another. The body of one ‘for’ loop contains the other and so on. The syntax of a nested for loop is as follows (using two for loops): Let's have a look at the below example:
Syntax:
for(initialization; test; update)
{
for(initialization; test; update) //using another variable
{
//body of the inner loop
}
//body of outer loop(might or might not be present)
}
/*Program to prints a triangular pattern numbers*/
#include <stdio.h>
int main()
{
int i,j;
for(i=1; i<=5; i++)
{
for(j=1; j<=i; j++)
printf("%d", j);
printf("\n");
}
return 0;
}
Output
1
12
123
1234
12345
Explanation:
Above program prints a triangular pattern. Now, the outer loop starts with i=1 and checks the condition whether i<= 5 is true or not which is true so the control goes on the body which contains another loop. This loop starts with the initial value as j=1 and checks if j<=i which is true and hence prints the value of j.
In the next iteration, the condition of the inner loop becomes false and the control exits the inner loop and changes the line. Now it goes for the next iteration of the outer loop and the process goes on. unless the condition becomes false and the loop terminates and the program ends.
// Example of nested for loop:
#include <stdio.h>
int main()
{
for(i=0; i<2; i++)
{
for(j=0; j<=3; j++)
{
printf("%d, %d\n", i, j);
{
sum += count;
}
return 0;
}
Output
0, 0
0, 1
0, 2
0, 3
1, 0
1, 1
1, 2
1, 3
- What is loop?
- For loop
- While loop
- do...while loop
0 Comments:
Post a Comment
Please don't enter any spam link in the comment box.