Tutorial 6.4: Nested Loop

Nested Loop
Remember nested if, the same can be applied to repetition structure. A loop within a loop is called nested loop. Any type of loop can be placed in any type of loop. Its means, you can put a while loop in a for loop, do while loop in a while loop etc. The following is an example of nested loop.
#include <stdio.h>

int main()
{
 int i, j;
 for(i = 1; i < 11; ++i) {
  j = 1;
  sum = 0;
  do {
   sum += j++;
  } while(j <= i);
  printf("%d\t\t%d\n", i, sum);
 }
 return 0;
}
Sample output:

1 1
2 3
3 6
4 10
5 15
6 21
7 28
8 36
9 45
10 55


Explanation:

The program computes the sum of all numbers from 1 up to the value of j which is 10. Lets look at the loop structure.
for(i = 1; i < 11; ++i) {
 j = 1;
 sum = 0;
 do {
  sum += j++;
 } while(j <= i);
 printf("%d\t\t%d\n", i, sum);
}
The for loop is called the outer loop and the do while loop is called inner loop. Each time outer loop is repeated, inner loop will be executed and all its iteration are performed. This means, inner loop is executed or all its iteration are completed 10 in this example since the outer loop is repeated 10 times.

The for loop begins by assigning value of 1 to i. The loop condition is i < 11 thus the for loop will repeat for 10 times. For each iteration of for loop, variable sum is initialise to 0 and the do while is executed.
do {
 sum += j++;
} while(j <= i);
The do while loop computes the sum of all values of j each time j is incremented until the current value of i. You may wonder what is the statement
 sum += j++;
is doing. Actually that statement is equivalent to
 sum = sum + j;
 j++;
Next: Infinite Loop

1 comment:

Unknown said...

#include

int main()
{
int sum;
int i, j;
for(i = 1; i < 11; ++i) {
j = 1;
sum = 0;
do {
sum += j++;
} while(j <= i);
printf("%d\t\t%d\n", i, sum);
}
return 0;
}
you should write divination for sum

Post a Comment