0
0
Javaprogramming~10 mins

Why loops are 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 loop.

Java
for(int i = 1; i <= [1]; i++) {
    System.out.println(i);
}
Drag options to blanks, or click blank then click option'
A10
B1
C5
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using 10 instead of 5 makes the loop run too many times.
Using 0 will not print any numbers because i starts at 1.
2fill in blank
medium

Complete the code to sum numbers from 1 to 4 using a loop.

Java
int sum = 0;
for(int i = 1; i <= [1]; i++) {
    sum += i;
}
System.out.println(sum);
Drag options to blanks, or click blank then click option'
A4
B3
C5
D6
Attempts:
3 left
💡 Hint
Common Mistakes
Using 5 will add an extra number.
Using 3 will miss the number 4.
3fill in blank
hard

Fix the error in the loop condition to print numbers from 0 to 3.

Java
for(int i = 0; i [1] 3; i++) {
    System.out.println(i);
}
Drag options to blanks, or click blank then click option'
A>
B<
C==
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using < will stop before printing 3.
Using == will only run once when i is 3.
4fill in blank
hard

Fill both blanks to create a loop that prints even numbers from 2 to 6.

Java
for(int i = [1]; i [2] 6; i += 2) {
    System.out.println(i);
}
Drag options to blanks, or click blank then click option'
A2
B<=
C<
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 1 will print odd numbers.
Using < will miss printing 6.
5fill in blank
hard

Fill all three blanks to create a loop that prints numbers from 5 down to 1.

Java
for(int i = [1]; i [2] 1; i [3]) {
    System.out.println(i);
}
Drag options to blanks, or click blank then click option'
A5
B>=
C--
D++
Attempts:
3 left
💡 Hint
Common Mistakes
Using ++ will increase i and cause an infinite loop.
Using <= will never run because 5 is not less than or equal to 1.