C Programming Tutorial
Computer Tutorial

Nesting of Loops



Nesting of Loops

The way if statements can be nested, similarly whiles and for's can also be nested. To understand how nested loops work, look at the program given below:

\* C Program to show the use of Nesting of Loop *\
# include < stdio.h >
int   main( )
{

int   r, c, sum  ;
for ( r = 1 ; r <= 3 ; r++  )
{

for ( c = 1 ; c <= 2 ; c++  )
{

sum = r + c ;
printf("\n r = %d c = %d sum = %d ",   r, c, sum) ;

}

}
return ( 0 );

}

When you run this program you will get the following output :

r = 1 c = 1 sum = 2
r = 1 c = 2 sum = 3
r = 2 c = 1 sum = 3
r = 2 c = 2 sum = 4
r = 3 c = 1 sum = 4
r = 3 c = 2 sum = 5