0
0
Javaprogramming~10 mins

Why while loop is needed in Java - Test Your Understanding

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print numbers from 1 to 5 using a while loop.

Java
int i = 1;
while (i [1] 5) {
    System.out.println(i);
    i++;
}
Drag options to blanks, or click blank then click option'
A<=
B<
C>
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using > or >= will cause the loop to never run or run incorrectly.
2fill in blank
medium

Complete the code to keep asking the user for input until they enter 0.

Java
Scanner scanner = new Scanner(System.in);
int num;
do {
    System.out.print("Enter a number: ");
    num = scanner.nextInt();
} while (num [1] 0);
Drag options to blanks, or click blank then click option'
A==
B<
C!=
D>
Attempts:
3 left
💡 Hint
Common Mistakes
Using == will stop the loop immediately if the first input is not zero.
3fill in blank
hard

Fix the error in the while loop condition to avoid an infinite loop.

Java
int count = 0;
while (count [1] 5) {
    System.out.println(count);
    count++;
}
Drag options to blanks, or click blank then click option'
A<
B<=
C>
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using >= or > will cause the loop to never run.
4fill in blank
hard

Fill both blanks to create a while loop that prints even numbers less than 10.

Java
int num = 0;
while (num [1] 10) {
    if (num % 2 == 0) {
        System.out.println(num);
    }
    num[2];
}
Drag options to blanks, or click blank then click option'
A<
B++
C--
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using -- will decrease num and cause an infinite loop.
5fill in blank
hard

Fill all three blanks to create a while loop that sums numbers from 1 to 5.

Java
int sum = 0;
int i = 1;
while (i [1] 5) {
    sum [2] i;
    i[3];
}
System.out.println(sum);
Drag options to blanks, or click blank then click option'
A<=
B+=
C++
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using < instead of <= will miss adding 5 to sum.
Forgetting to increment i causes infinite loop.