nerdexam
Oracle

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.

Using Loop Constructs

Question

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 result?

Options

  • A4
  • B4
  • C4321
  • D4567

How the community answered

(15 responses)
  • A
    80% (12)
  • B
    13% (2)
  • C
    7% (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.

A4Correct

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.

B4

This is a duplicate of option A, which correctly represents the first line of output.

C4321

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.

D4567

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

#nested loops#for loop#while loop

Community Discussion

No community discussion yet for this question.

Full 1Z0-803 Practice