Concept
How do nested loops execute in C?
ComputerScienceOne / Paying the Piper
"Recall that you can write loops within loops. The inner loop will execute fully for each iteration of the outer loop. An example of two nested loops in C can be found in Code Sample 17.7.\n\nint i, j;\n\nint n = 10;\n\nint m = 20;\n\nfor(i=0; i<n; i++) {\n\nfor(j=0; j<m; j++) {\n\nprintf(\"(i, j) = (%d, %d)\n\n\", i, j);\n\n}\n\n}\n\nCode Sample 17.7.: Nested For Loops in C\n\nThe inner loop executes for j = 0, 1, 2, . . . , 19 < m = 20 for a total of 20 iterations. However, it executes 20 times for each iteration of the outer loop. Since the outer loop executes for i = 0, 1, 2, . . . , 9 < n = 10, the total number of times the printf() statement executes is 10 × 20 = 200. In this example, the sequence (0, 0), (0, 1), (0, 2), . . . , (0, 19), (1, 0), . . . , (9, 19) will be printed."
Related Ideas
- How do nested loops execute in C?ComputerScienceOne · Nested Loops
- How do nested loops execute in Java?ComputerScienceOne · Nested Loops
- How do nested for loops execute in PHP?ComputerScienceOne · Nested Loops
- What are nested for loops in C?ComputerScienceOne · Summation of Numbers using a For Loop in C . . . . . . . . . . . . . . .
- How do you compute a summation with a for loop in C?ComputerScienceOne · Summation
- How are for loops structured and scoped in Java?ComputerScienceOne · Do-While Loops
- How do do-while loops differ from while loops in C?ComputerScienceOne · For Loops
- How can you simulate a foreach loop when iterating over an array in C?ComputerScienceOne · Other Issues