Nesting of Loops in C

Rate this post

The way if statements can be nested, similarly whiles and for can also be nested.

To understand how nested loops work, look at the program given below:

/* Example of nested loops */

main( )
int r, c, sum ;
for ( r = 1 ; r <= 3 ; r++ ) /* outer loop */
for ( c = 1 ; c <= 2 ; c++ ) /* inner loop */
sum = r + c ;
printf ( “r = %d c = %d sum = %d\n”, r, c, sum ) ;

After running 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

Here, for each value of r the inner loop is cycled through twice, with the variable c taking values from 1 to 2.

The inner loop terminates when the value of c exceeds 2, and the outer loop terminates when the value of r exceeds 3.

As you can see, the body of the outer for loop is indented, and the body of the inner for loop is further indented. These multiple indentations make the program easier to understand. Instead of using two statements, one to calculate sum and another to print it out, we can compact this into one single statement by saying:
printf ( “r = %d c = %d sum = %d\n”, r, c, r + c ) ;

The way for loops have been nested here, similarly, two while loops can also be nested. Not only this, a for loop can occur within a while loop, or a while within a for.

Multiple Initialisations in the for Loop

The initialisation expression of the for loop can contain more than one statement separated by a comma.
For example,

for ( i = 1, j = 2 ; j <= 10 ; j++ )

Multiple statements can also be used in the incrementation expression of for loop; i.e., you can increment (or decrement) two or more variables at the same time. However, only one expression is allowed in the test expression. This expression may contain several conditions linked together using logical operators.

Use of multiple statements in the initialisation expression also demonstrates why semicolons are used to separate the three expressions in the for loop. If commas had been used, they could not also have been used to separate multiple statements in the initialisation expression, without confusing the compiler.

For any query or issue, feel free to discuss on

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: