0
0
Javaprogramming~20 mins

Why while loop is needed in Java - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
While Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why use a while loop instead of an if statement?

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?

ABecause <code>if</code> is used for loops and <code>while</code> is used for single checks.
BBecause <code>if</code> can repeat the input multiple times automatically, but <code>while</code> cannot.
CBecause <code>while</code> repeats the check and input until the condition is false, but <code>if</code> only checks once.
DBecause <code>while</code> runs only once and <code>if</code> runs multiple times.
Attempts:
2 left
💡 Hint

Think about how many times the program needs to check the user's input.

Predict Output
intermediate
2:00remaining
Output of a while loop example

What will be the output of this Java code?

Java
int count = 1;
while (count <= 3) {
    System.out.print(count + " ");
    count++;
}
ANo output
B1 2 3 4
C1 2
D1 2 3
Attempts:
2 left
💡 Hint

Count starts at 1 and increases by 1 each time until it is greater than 3.

🔧 Debug
advanced
2:00remaining
Identify the problem with this while loop

What error or problem will this code cause?

Java
int i = 0;
while (i < 5) {
    System.out.println(i);
}
AInfinite loop because <code>i</code> is never increased.
BSyntax error because <code>while</code> needs a semicolon after the condition.
CPrints numbers 0 to 4 correctly.
DNo output because the loop condition is false at start.
Attempts:
2 left
💡 Hint

Check if the loop variable changes inside the loop.

📝 Syntax
advanced
2:00remaining
Which code snippet correctly uses a while loop?

Choose the code that correctly uses a while loop in Java.

A
while i &lt; 5 {
  System.out.println(i);
  i++;
}
B
while (i &lt; 5) {
  System.out.println(i);
  i++;
}
C
while (i &lt; 5)
  System.out.println(i)
  i++;
D
while (i &lt; 5) {
  System.out.println(i);
  i++
}
Attempts:
2 left
💡 Hint

Remember Java syntax for loops requires parentheses and braces.

🚀 Application
expert
2:00remaining
Using while loop to sum user inputs until zero

What is the value of sum after running this code if the user inputs: 4, 3, 2, 0?

Java
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);
A9
B0
C10
DInfinite loop
Attempts:
2 left
💡 Hint

Remember the loop adds the input number to sum before checking if it is zero.