1Z0-803 · Question #154
Given the code fragment: 12. for (int row = 4; row > 0; row--) { 13. int col = row; 14. while (col <= 4) { 15. System.out.print(col); 16. col++; 17. } 18. System.out.println(); 19. } What is the resul
The correct answer is A. 4. The code features nested loops where an outer for loop iterates row from 4 down to 1. An inner while loop, for each row, prints numbers from row up to 4 on the same line, followed by a newline character.
Question
Options
- A4
- B4
- C4321
- D4567
How the community answered
(15 responses)- A80% (12)
- B13% (2)
- C7% (1)
Why each option
The code features nested loops where an outer `for` loop iterates `row` from 4 down to 1. An inner `while` loop, for each `row`, prints numbers from `row` up to 4 on the same line, followed by a newline character.
In the first iteration of the outer loop, `row` is initialized to 4. Inside the loop, `col` is set to 4. The `while (col <= 4)` loop then prints `col` (which is `4`) and increments `col` to 5. After this, `col <= 4` becomes false, terminating the inner loop, and a newline is printed. This results in '4' on the first line of output.
This is a duplicate of option A, which correctly represents the first line of output.
The sequence '4321' does not appear as a single line in the program's output, as numbers are printed in ascending order within each line.
The sequence '4567' does not appear as a single line in the program's output, and the inner loop's condition `col <= 4` prevents numbers greater than 4 from being printed.
Concept tested: Java nested loops and control flow
Source: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
Topics
Community Discussion
No community discussion yet for this question.