0
0
Javaprogramming~20 mins

Loop initialization, condition, update in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a for-loop with multiple updates
What is the output of the following Java code?
Java
public class Main {
    public static void main(String[] args) {
        int sum = 0;
        for (int i = 1, j = 10; i < j; i += 2, j -= 3) {
            sum += i + j;
        }
        System.out.println(sum);
    }
}
A21
B50
C45
D55
Attempts:
2 left
💡 Hint
Trace the values of i and j in each loop iteration and add their sum.
Predict Output
intermediate
2:00remaining
Output of a while-loop with complex condition
What is the output of this Java code snippet?
Java
public class Main {
    public static void main(String[] args) {
        int i = 0;
        int count = 0;
        while (i < 10) {
            i += 3;
            if (i % 2 == 0) {
                count++;
            }
        }
        System.out.println(count);
    }
}
A5
B3
C4
D2
Attempts:
2 left
💡 Hint
Check the values of i after each increment and count how many are even.
🔧 Debug
advanced
2:00remaining
Identify the error in loop initialization
What error will this Java code produce when compiled?
Java
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++)
            int j = i * 2;
        System.out.println(j);
    }
}
ACompilation error: variable j might not have been initialized
BCompilation error: cannot find symbol j
CRuntime error: NullPointerException
DOutput: 8
Attempts:
2 left
💡 Hint
Check the scope of variable j declared inside the loop.
Predict Output
advanced
2:00remaining
Output of nested for-loops with update expressions
What is the output of this Java program?
Java
public class Main {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 1; i <= 3; i++) {
            for (int j = i; j <= 3; j += 2) {
                count++;
            }
        }
        System.out.println(count);
    }
}
A7
B6
C4
D8
Attempts:
2 left
💡 Hint
Count how many times the inner loop runs for each i.
🧠 Conceptual
expert
2:00remaining
Effect of loop update expression on iteration count
Consider the loop:
for (int i = 0; i < 20; i += 4) { /* body */ }

How many times will the loop body execute?
A5
B4
C6
D7
Attempts:
2 left
💡 Hint
Count how many increments of 4 fit before i reaches 20.