Nested Loops in C

by Dinesh Thakur Category: Control Structures

The C language provides three loops (for,while and do ...while).As contained statement in the body of the loop can be any valid C statement, we can obtain several nested-loop structures by replacing this statement with another loop statement. Thus, if we replace the statement in a for loop with another for loop, we will get a two-level nested for loop as

for ( initial_exprl ; final_exprl ; update_exprl )

{

for ( initial_expr2 ; jinal_expr2 ; update_expr2)

{

statement;

}

}

Observe that the inner for loop is executed once for each iteration of the outer for loop. Thus, if the outer and inner loops are set up to perform m and n iterations, respectively, the statement contained within the inner for loop will be executed m x n times. Also note the use of curly braces to improve code readability. The two-level nested for loops are commonly used for operations with two-dimensional arrays, i. e., matrices.

The general forms for two-level nested while and do ...while loops are given below.

while ( expr1 )                          do

{                                                   {

while ( expr2)                              do {

{                                                             statement ;

statement;                                  } while ( expr2 ) ;

}                                                } while ( expr1 ) ;

}

If we replace the contained statement within a for loop with a while or do ...while statement, we can get other forms of two-level nested loops as shown below.

for ( initial_expr ; final_expr; update_expr)

{

while ( expr )

{

statement ;

}

}

for ( initial_expr ; final_ expr ; update_expr )

{

do

{

statement ;

} while ( expr ) ;

}

Similarly, by replacing the statement contained within the while and do ...while loops with other types of loop statements, we can obtain other general forms of nested loops.

Note that as the statement contained within two-level nested loops can also be any valid C statement including a control statement, we can obtain higher levels of nested loops. Thus, we can replace the statement contained in a two-level nested for loop given above with another for loop to obtain a three-level nested for loop as shown below.

for ( initial_exprl ; .final_exprl ; update_exprl ) {

for ( initial_expr2; final_expr2; update_expr2) {

for ( initial_expr3 ; final_expr3 ; update_expr3)

statement ;

}

}

}

Such nested for loops are used for operations with three-dimensional arrays and also to perform matrix multiplication operations.

Dinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Search Content

Popular Article