Nested loop

The statement block of a loop lies completely inside the block of another loop. This is referred as nested loop. Any number of statements can be nested. Consider the following example using two for loops.

for (i = 1; i <=3; 1++)
    {
        . . . 
        for (j = 1; j<=5; j++)
        {
            . . . 
            /*statement block*/
             . . . 
          }
             . . .
               }

Note that the markers { } can be omitted if there is only one statement in statement block. When this statement is executed, the computer assigns i = 1 and the inner loop is executed 5 times for j varies from 1 to 5 in steps of 1. Then i is incremented by 1 (i.e., i=2) and the inner loop executed 5 times for j to 5. Then i becomes 3 and the inner loop is executed 5 times. Note that the statement clock is executed and repeated 15 times (3X5 =15).

Program sum the following series using nested for loop

S = 1 +(1+2) + (1+2+3) +. . .+ (1+2+3) +. . .+N)

#include<stdio.h>
    #include<conia.h>
    Main ()
    {
        int i, j, sum, term;
        clrscr ();
        printf (“\Enter the value for N: “);
        scanf (“%d”, &n);
        sum = 0;
        for (i =1; i<=n; j++)
         {
        Term = 0;
        for (j=1; j<i; j++)
              {
             Term = term+j
         }
                Sum = sum + term;
           }
           printf (“\n\nsum of the series is %7d”, sum);
           getch ();
      }

Output

Enter the value of N: 4
Sum of series is 20



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext