Recall & Review
beginner
What is the basic syntax of a for loop in Java?
A for loop in Java has three parts inside parentheses: initialization, condition, and update. It looks like this:<br>
for (int i = 0; i < 5; i++) {<br> // code to repeat<br>}Click to reveal answer
beginner
What does the 'initialization' part in a for loop do?
Initialization sets up a starting point before the loop runs. Usually, it creates and sets a variable, like
int i = 0;.Click to reveal answer
beginner
What happens if the condition in a for loop is false at the start?
If the condition is false at the start, the loop body does not run even once. The program skips the loop and continues after it.
Click to reveal answer
beginner
What is the role of the update part in a for loop?
The update part changes the loop variable after each run. For example,
i++ adds 1 to i each time, moving the loop forward.Click to reveal answer
beginner
Can you write a for loop that prints numbers from 1 to 3 in Java?
Yes! Here's how:<br>
for (int i = 1; i <= 3; i++) {<br> System.out.println(i);<br>}This prints:<br>1<br>2<br>3Click to reveal answer
Which part of the for loop controls how many times the loop runs?
✗ Incorrect
The condition is checked before each loop run. If it's true, the loop runs; if false, it stops.
What does this for loop do?<br>
for (int i = 0; i < 3; i++) { System.out.print(i); }✗ Incorrect
The loop starts at 0 and runs while i is less than 3, printing 0, 1, and 2.
What happens if you forget to update the loop variable in a for loop?
✗ Incorrect
Without updating, the condition may never become false, causing an infinite loop.
Which part of the for loop is optional in Java?
✗ Incorrect
Initialization, condition, and update can all be omitted in Java, but usually at least the condition is needed to avoid infinite loops.
What is printed by this code?<br>
for (int i = 5; i > 0; i--) { System.out.print(i + " "); }✗ Incorrect
The loop starts at 5 and decreases i by 1 each time until i is 1.
Explain the three parts of a for loop in Java and their roles.
Think about starting value, when to stop, and how to change the counter.
You got /4 concepts.
Write a simple for loop in Java that prints the numbers 1 to 5.
Use System.out.println inside the loop.
You got /5 concepts.