Bifalgorithm post · Computer science one · Nested Loops

How do nested loops execute in Java?

How do nested loops execute in Java? (Computer science one · Nested Loops) — "28.5.3. Nested Loops\n\nRecall that you can write loops within loops by nesting t…

Ideas in this flowchart

  • Nested loops execute one loop inside another.
  • A loop can be written within another loop.
  • The inner loop executes completely for each iteration of the outer loop.
  • Java example: two nested for loops.
  • The example sets n = 10 and m = 20.
  • The outer loop iterates with i = 0, 1, 2, …, 9.
  • The inner loop iterates with j = 0, 1, 2, …, 19.
  • System.out.printf() prints each pair (i, j).
  • The statement executes 10 × 20 = 200 times.
  • The printed sequence ranges from (0, 0) through (9, 19).
Feed/

How do nested loops execute in Java?

No cover

Channel

Computer science one

1 page

"28.5.3. Nested Loops\n\nRecall that you can write loops within loops by nesting them. The inner loop will execute fully for each iteration of the outer loop. An example of two nested of loops in Java can be found in Code Sample 28.9.\n\n1 int i, j;\n\n2 int n = 10;\n\n3 int m = 20;\n\n4 for(i=0; i<n; i++) {\n\n5 for(j=0; j<m; j++) {\n\n6 System.out.printf(\"(i, j) = (%d, %d)\n\n\", i, j);\n\n7 }\n\n8 }\n\nCode Sample 28.9.: Nested For Loops in Java\n\nThe inner loop execute 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 execute for i = 0, 1, 2, . . . , 9 < n = 10, the total number of times the System.out.printf() statement execute is 10 × 20 = 200. In this example, the sequence (0, 0), (0, 1), (0, 2), . . . , (0, 19), (1, 0), . . . , (9, 19) will be printed."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.