Nested Loop C

A loop can occur within another loop. The inner loop is said to be nested in the outer loop. We have seen nesting of decision control statement) i.e. if-else statement). Similarly while and for loops can be nested within one another. Nesting can go upto any level. Each level should be controlled by different index. It is obvious that the index should be relevant to each other.

/* program to demonstrate use of nested loops */
/* one for-loop nested within another for-loop */

Output of above program is
r = 1 c = 1 sum = 2
r = 1 c = 2 sum = 3
r = 2 c = 1 sum = 3
r = 2 c = 2 sum = 4

For each value of r, the inner loop is executed two times with c running from 1 to 2 and terminates when c exceeds 2. Value of r ranges from 1 to 3 and terminates when r exceeds 3.

It is necessary that one loop should be completely embedded within another loop. There should be no loop overlapping.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C Topics