0
0
Javaprogramming~20 mins

For loop syntax in Java - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
For Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a basic for loop
What is the output of this Java code?
Java
public class Main {
    public static void main(String[] args) {
        for (int i = 0; i < 3; i++) {
            System.out.print(i + " ");
        }
    }
}
A0 1 2 3
B0 1 2
C1 2 3
D1 2 3 4
Attempts:
2 left
💡 Hint
Remember the loop runs while i is less than 3, starting from 0.
🧠 Conceptual
intermediate
1:30remaining
Understanding for loop components
Which part of the for loop controls how many times the loop runs?
AThe condition part
BThe initialization part
CThe update part
DThe body of the loop
Attempts:
2 left
💡 Hint
Think about what decides if the loop continues or stops.
Predict Output
advanced
2:30remaining
Output with multiple variables in for loop
What is the output of this Java code?
Java
public class Main {
    public static void main(String[] args) {
        for (int i = 0, j = 3; i < 3; i++, j--) {
            System.out.print(i + "-" + j + " ");
        }
    }
}
A0-3 1-2 2-1
B0-3 1-2 2-1 3-0
C1-2 2-1 3-0
D0-3 1-2 2-1 3-0 4--1
Attempts:
2 left
💡 Hint
Both i and j change each loop; watch their values carefully.
🔧 Debug
advanced
2:00remaining
Identify the error in this for loop
What error does this Java code produce?
Java
public class Main {
    public static void main(String[] args) {
        for int i = 0; i < 5; i++) {
            System.out.print(i);
        }
    }
}
ANo error, code runs fine
BSyntaxError: Missing semicolon after initialization
CSyntaxError: Missing curly braces around loop body
DSyntaxError: Missing parentheses around for loop header
Attempts:
2 left
💡 Hint
Check the syntax of the for loop header carefully.
🚀 Application
expert
3:00remaining
Number of iterations in nested for loops
How many times does the inner loop run in total when this code executes?
Java
public class Main {
    public static void main(String[] args) {
        int count = 0;
        for (int i = 1; i <= 4; i++) {
            for (int j = 1; j <= i; j++) {
                count++;
            }
        }
        System.out.println(count);
    }
}
A16
B8
C10
D12
Attempts:
2 left
💡 Hint
Count how many times the inner loop runs for each i from 1 to 4.