Consider a situation where you want to keep asking a user for input until they enter a valid number. Why is a while loop better than an if statement here?
Think about how many times the program needs to check the user's input.
A while loop keeps running as long as the condition is true, so it can repeatedly ask for input until the user enters a valid number. An if statement only checks once and does not repeat.
What will be the output of this Java code?
int count = 1; while (count <= 3) { System.out.print(count + " "); count++; }
Count starts at 1 and increases by 1 each time until it is greater than 3.
The loop prints the value of count while it is less than or equal to 3. So it prints 1, then 2, then 3, then stops.
What error or problem will this code cause?
int i = 0; while (i < 5) { System.out.println(i); }
Check if the loop variable changes inside the loop.
The variable i is never incremented inside the loop, so the condition i < 5 is always true, causing an infinite loop.
Choose the code that correctly uses a while loop in Java.
Remember Java syntax for loops requires parentheses and braces.
Option B uses correct Java syntax: parentheses around the condition and braces to group statements inside the loop.
What is the value of sum after running this code if the user inputs: 4, 3, 2, 0?
import java.util.Scanner; Scanner sc = new Scanner(System.in); int sum = 0; int num = -1; while (num != 0) { num = sc.nextInt(); sum += num; } sc.close(); System.out.println(sum);
Remember the loop adds the input number to sum before checking if it is zero.
The inputs are 4, 3, 2, 0. The loop adds all inputs including zero. So sum = 4 + 3 + 2 + 0 = 9. But the code adds zero as well, so sum is 9. Wait, check carefully: sum starts at 0, first input 4 added → 4, then 3 → 7, then 2 → 9, then 0 → 9. So sum is 9. But option A says 10, option A says 9. So correct answer is A.