Free AP CSA Control Structures Questions and Answers — Questions and Answers
Question 1: What will be the output of the following code?
- A (Correct answer)
- B
- No output
- Compilation error
Correct answer: A
The code initializes an integer `x` with the value `10`. The `if` condition `(x > 5)` evaluates to `true` because `10` is indeed greater than `5`. Consequently, the statement inside the `if` block, `System.out.print("A")`, is executed, printing "A" to the console. The `else` block is skipped.
Question 2: What will be the output of this code?
- Wednesday
- Wednesday Invalid day (Correct answer)
- Invalid day
- Error
Correct answer: Wednesday Invalid day
The `switch` statement evaluates the `day` variable, which is "Wednesday". It matches the `case "Wednesday"`, causing "Wednesday" to be printed. Crucially, there is no `break` statement after this `case` block, leading to 'fall-through'. This means the execution continues to the `default` block, which then prints "Invalid day" immediately after "Wednesday".
Question 3: How many times will the following loop execute?
- 4
- 5 (Correct answer)
- Infinite
- 6
Correct answer: 5
The `for` loop initializes `i` to `0` and continues as long as `i` is less than `5`. The loop iterates for `i` values `0, 1, 2, 3, 4`. Therefore, the loop body will execute exactly five times, once for each of these values.
Question 4: What is the output of this code?
- 0 1 2 3 4
- 0 1 2 (Correct answer)
- 0 1 2 3
- 3 4
Correct answer: 0 1 2
The `for` loop initializes `i` to `0`. In each iteration, `i` is printed, followed by a space. When `i` becomes `3`, the `if (i == 3)` condition is met, and the `break` statement is executed. The `break` immediately terminates the loop, preventing `3` and any subsequent numbers from being printed.
Question 5: What is the output of the following code?
- 0,0 0,1 0,2
- 0,0 0,1 0,2 1,0 1,1 1,2 (Correct answer)
- 0,0 1,0
- 0,0 0,1 1,0 1,1
Correct answer: 0,0 0,1 0,2 1,0 1,1 1,2
This code uses nested `for` loops. The outer loop iterates for `i = 0` and `i = 1`. For each iteration of the outer loop, the inner loop completes its full cycle, iterating for `j = 0, 1, 2`. This results in the output: `0,0 0,1 0,2` (for `i=0`) followed by `1,0 1,1 1,2` (for `i=1`).
What will be the output of the following code?