Nested Loops

I l @ ve RuBoard

Nested Loops

A nested loop is one loop inside another loop. A common use for nested loops is to display data in rows and columns. One loop can handle, say, all the columns in a row, and the second loop handles the rows. Listing 6.15 shows a simple example.

Listing 6.15 The rows1.c program.
 /* rows1.c -- uses nested loops */ #include <stdio.h> #define ROWS  6 #define CHARS 10 int main(void) {     int row;     char ch;     for (row = 0; row < ROWS; row++)              /* line 10 */     {         for (ch = 'A'; ch ;lt ('A' + CHARS); ch++)  /* line 12 */             printf("%c", ch);         printf("\n");     }     return 0; } 

Running the program produces this output:

 ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ ABCDEFGHIJ 

Discussion

The for loop beginning on line 10 is called an outer loop, and the loop beginning on line 12 is called an inner loop because it is inside the other loop. The outer loop starts with row having a value of and terminates when row reaches 6 . Therefore, the outer loop goes through six cycles, with row having the values through 5 . The first statement in each cycle is the inner for loop. This loop goes through ten cycles, printing the characters A through J on the same line. The second statement of the outer loop is printf("\n"); . This statement starts a new line so that the next time the inner loop is run, the output is on a new line.

Note that, with a nested loop, the inner loop runs through its full range of iterations for each single iteration of the outer loop. In the last example, the inner loop prints ten characters to a row, and the outer loop creates six rows.

A Nested Variation

In the preceding example, the inner loop did the same thing for each cycle of the outer loop. You can make the inner loop behave differently each cycle by making part of the inner loop depend on the outer loop. Listing 6.16, for example, alters the last program slightly by making the starting character of the inner loop depend on the cycle number of the outer loop.

Listing 6.16 The rows2.c program.
 /* rows2.c -- using dependent nested loops */ #include <stdio.h> #define ROWS  6 #define CHARS 6 int main(void) {     int row;     char ch;     for (row = 0; row < ROWS; row++)     {         for (ch = ('A' + row);  ch < ('A' + CHARS); ch++)             printf("%c", ch);         printf("\n");     }      return 0; } 

This time the output is as follows :

 ABCDEF BCDEF CDEF DEF EF F 

Because row is added to "A" during each cycle of the outer loop, ch is initialized in each row to one character later in the alphabet. The test condition, however, is unaltered, so each row still ends on F . This results in one fewer character being printed in each row.

I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net