0
0
Javaprogramming~5 mins

Counter-based while loop in Java - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a counter-based while loop?
A counter-based while loop repeats a block of code while a counter variable meets a condition, usually increasing or decreasing the counter each time to eventually stop the loop.
Click to reveal answer
beginner
Why do we need a counter variable in a while loop?
The counter variable helps control how many times the loop runs. It changes each time the loop runs so the loop can stop when the counter reaches a limit.
Click to reveal answer
beginner
What happens if the counter is not updated inside a while loop?
If the counter is not updated, the loop condition may never become false, causing an infinite loop that runs forever.
Click to reveal answer
beginner
Example: What does this code print? int i = 1; while (i <= 3) { System.out.println(i); i++; }
It prints: 1 2 3 The loop starts with i=1 and prints i, then increases i by 1 each time until i is greater than 3.
Click to reveal answer
beginner
How to avoid infinite loops in counter-based while loops?
Always update the counter inside the loop so the condition will eventually become false. Also, check the loop condition carefully before running the loop.
Click to reveal answer
What is the role of the counter in a counter-based while loop?
ATo store the output of the loop
BTo stop the program immediately
CTo control how many times the loop runs
DTo print messages inside the loop
What happens if you forget to increase the counter inside a while loop?
AThe program will crash immediately
BThe loop will run forever (infinite loop)
CThe loop will run only once
DThe counter will automatically increase
Which of these is a correct way to start a counter for a while loop that runs 5 times?
AAll of the above
Bint count = 5; while (count > 0) { ... count--; }
Cint count = 1; while (count <= 5) { ... count++; }
Dint count = 0; while (count < 5) { ... count++; }
What will this code print? int i = 3; while (i > 0) { System.out.println(i); i--; }
ANothing
B1 2 3
C0 1 2
D3 2 1
Which part of a counter-based while loop changes each time the loop runs?
AThe counter variable
BThe loop condition
CThe program output
DThe loop keyword
Explain how a counter-based while loop works and why the counter must be updated inside the loop.
Think about how the loop knows when to stop.
You got /4 concepts.
    Write a simple Java while loop that prints numbers from 1 to 5 using a counter.
    Start with int i = 1; and use i <= 5 as condition.
    You got /4 concepts.