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 ...
Get C Primer Plus®, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.