Practice Questions — Loops in Java (for, while, do-while)
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output?
for (int i = 1; i <= 5; i++) {
System.out.print(i + " ");
}i goes from 1 to 5 inclusive.
1 2 3 4 5 Question 2
Easy
What is the output?
for (int i = 5; i >= 1; i--) {
System.out.print(i + " ");
}Counting downward from 5 to 1.
5 4 3 2 1 Question 3
Easy
What is the output?
int x = 1;
while (x <= 3) {
System.out.println("Hello");
x++;
}x starts at 1 and increments to 4.
HelloHelloHelloQuestion 4
Easy
What is the output?
int n = 10;
do {
System.out.println(n);
n++;
} while (n < 5);do-while executes the body at least once before checking the condition.
10Question 5
Easy
What is the output?
for (int i = 0; i < 5; i++) {
System.out.print(i + " ");
}Starts at 0, goes up to but not including 5.
0 1 2 3 4 Question 6
Medium
What is the output?
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.print(i + "" + j + " ");
}
}
Inner loop runs completely for each outer iteration.
11 12 21 22 31 32 Question 7
Medium
What is the output?
int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
sum += i;
}
}
System.out.println(sum);Sum of even numbers from 1 to 10.
30Question 8
Medium
What is the output?
for (int i = 1; i <= 4; i++) {
if (i == 3) continue;
System.out.print(i + " ");
}continue skips the rest of the current iteration.
1 2 4 Question 9
Medium
How many times does "Hello" print?
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
System.out.println("Hello");
}
}Outer: 3 iterations. Inner: 4 iterations each.
12 timesQuestion 10
Medium
What is the output?
int i = 5;
while (i > 0) {
System.out.print(i + " ");
i -= 2;
}i decreases by 2 each time: 5, 3, 1, then -1.
5 3 1 Question 11
Hard
What is the output?
for (int i = 0; i < 5; i++) {
if (i == 3) break;
System.out.print(i + " ");
}break exits the loop entirely when i equals 3.
0 1 2 Question 12
Hard
What is the output?
int x = 1;
for (int i = 1; i <= 4; i++) {
x *= i;
}
System.out.println(x);This computes x = 1 * 1 * 2 * 3 * 4.
24Question 13
Hard
What is the output?
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == j) continue;
System.out.print(i + "" + j + " ");
}
}continue in the inner loop skips pairs where i equals j.
12 13 21 23 31 32 Question 14
Medium
What is the difference between a while loop and a do-while loop? When would you choose one over the other?
Think about when the condition is checked.
A
while loop checks the condition before each iteration; if the condition is false initially, the body never executes. A do-while loop checks the condition after each iteration, so the body always executes at least once. Use do-while when the body must run at least once (menus, input validation). Use while when the body should not run if the condition is initially false.Question 15
Hard
Can you convert any for loop to a while loop and vice versa? Explain.
Think about the three parts of a for loop.
Yes, any for loop can be rewritten as a while loop and vice versa. A for loop
for (init; cond; update) { body; } is equivalent to init; while (cond) { body; update; }. However, a for loop's init variable has block scope (only visible inside the loop), while the while version's variable remains in the enclosing scope. The do-while loop is the exception: its guarantee of at least one execution can be replicated with a while loop by executing the body once before the loop or using a flag.Question 16
Easy
What is the output?
for (int i = 0; i < 3; i++) {
System.out.print("Hi ");
}i goes 0, 1, 2. Three iterations.
Hi Hi Hi Question 17
Medium
What is the output?
for (int i = 2; i <= 10; i += 3) {
System.out.print(i + " ");
}i starts at 2 and increases by 3: 2, 5, 8, 11.
2 5 8 Question 18
Medium
What is the output?
int[] arr = {4, 7, 2, 9};
int sum = 0;
for (int n : arr) {
sum += n;
}
System.out.println("Sum: " + sum);Add all elements: 4 + 7 + 2 + 9.
Sum: 22Question 19
Hard
What is the output?
int i = 1;
do {
System.out.print(i + " ");
i *= 2;
} while (i <= 16);i doubles: 1, 2, 4, 8, 16, then 32.
1 2 4 8 16 Question 20
Hard
What is the output?
for (int i = 100; i >= 1; i /= 3) {
System.out.print(i + " ");
}
Integer division: 100/3=33, 33/3=11, 11/3=3, 3/3=1, 1/3=0.
100 33 11 3 1 Mixed & Application Questions
Question 1
Easy
Write a program that prints even numbers from 2 to 20 using a for loop.
Start at 2, increment by 2.
for (int i = 2; i <= 20; i += 2) {
System.out.print(i + " ");
}Question 2
Easy
What is the output?
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum = sum + i;
}
System.out.println(sum);Add 1 + 2 + 3 + 4 + 5.
15Question 3
Medium
What is the output?
int i = 0;
while (i < 5) {
i++;
if (i == 3) continue;
System.out.print(i + " ");
}i is incremented before the continue check.
1 2 4 5 Question 4
Medium
Write a program to compute the factorial of a given number N using a while loop.
Factorial(5) = 5 * 4 * 3 * 2 * 1 = 120.
import java.util.Scanner;
public class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long factorial = 1;
int i = 1;
while (i <= n) {
factorial *= i;
i++;
}
System.out.println(n + "! = " + factorial);
sc.close();
}
}Question 5
Medium
What is the output?
for (int i = 10; i >= 1; i /= 2) {
System.out.print(i + " ");
}Integer division: 10/2=5, 5/2=2, 2/2=1, 1/2=0.
10 5 2 1 Question 6
Hard
What is the output?
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}Inner loop runs from 1 to i. So row 1 has 1 star, row 2 has 2, etc.
*
* *
* * *
* * * *
* * * * * Question 7
Hard
What is the output?
int count = 0;
for (int i = 2; i <= 20; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) count++;
}
System.out.println(count);Count prime numbers from 2 to 20.
8Question 8
Hard
What is the output?
int[] arr = {3, 7, 2, 8, 1};
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int n : arr) {
System.out.print(n + " ");
}This is the bubble sort algorithm.
1 2 3 7 8 Question 9
Hard
What is the output?
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 1) break;
System.out.print(i + "" + j + " ");
}
}break exits only the inner loop.
00 10 20 Question 10
Easy
Write a program that prints all numbers from 1 to 50 that are divisible by both 3 and 5.
Check if n % 15 == 0 (or n % 3 == 0 && n % 5 == 0).
for (int i = 1; i <= 50; i++) {
if (i % 3 == 0 && i % 5 == 0) {
System.out.print(i + " ");
}
}Question 11
Medium
What is the output?
int n = 5;
int result = 1;
for (int i = n; i >= 1; i--) {
result *= i;
}
System.out.println(result);This computes 5 * 4 * 3 * 2 * 1.
120Question 12
Hard
What is the output?
int count = 0;
for (int i = 1; i <= 100; i++) {
if (i % 7 == 0) count++;
}
System.out.println(count);Count multiples of 7 from 1 to 100.
14Question 13
Hard
What is the output?
String s = "Hello";
for (int i = s.length() - 1; i >= 0; i--) {
System.out.print(s.charAt(i));
}Iterate the string in reverse.
olleHMultiple Choice Questions
MCQ 1
Which loop is best when the number of iterations is known in advance?
Answer: C
C is correct. The
C is correct. The
for loop is designed for counted iterations with its init-condition-update structure.MCQ 2
How many times does the loop body execute?
for (int i = 0; i < 10; i++) { ... }Answer: B
B is correct. i takes values 0 through 9 (10 values). When i = 10,
B is correct. i takes values 0 through 9 (10 values). When i = 10,
10 < 10 is false, so the loop exits.MCQ 3
Which loop always executes its body at least once?
Answer: C
C is correct. The do-while loop checks its condition after the body executes, guaranteeing at least one execution.
C is correct. The do-while loop checks its condition after the body executes, guaranteeing at least one execution.
MCQ 4
What is the correct syntax for a for-each loop over an int array?
Answer: B
B is correct. Java's for-each syntax is
B is correct. Java's for-each syntax is
for (type variable : arrayOrCollection). The in keyword (option A) is not used in Java.MCQ 5
What does the continue statement do inside a loop?
Answer: B
B is correct.
B is correct.
continue skips the remaining body of the current iteration and jumps to the next iteration (checking the condition first).MCQ 6
What is the output?
for (int i = 1; i <= 3; i++) System.out.print(i); System.out.print(4);Answer: A
A is correct. Without curly braces, only the first statement after for is in the loop body. So print(i) runs 3 times (prints 123). Then print(4) runs once outside the loop (prints 4). Total: 1234.
A is correct. Without curly braces, only the first statement after for is in the loop body. So print(i) runs 3 times (prints 123). Then print(4) runs once outside the loop (prints 4). Total: 1234.
MCQ 7
Which creates an infinite loop?
Answer: C
C is correct.
C is correct.
for (;;) has no condition, which defaults to true, creating an infinite loop. while (false) never executes. do {} while (false) executes once and exits.MCQ 8
What happens if you put a semicolon after for (int i = 0; i < 5; i++);?
Answer: B
B is correct. The semicolon acts as an empty statement, becoming the loop body. The loop runs 5 times doing nothing. Any code in a block after it runs once, outside the loop.
B is correct. The semicolon acts as an empty statement, becoming the loop body. The loop runs 5 times doing nothing. Any code in a block after it runs once, outside the loop.
MCQ 9
Can you modify array elements using a for-each loop?
Answer: C
C is correct for primitive arrays. The for-each variable is a copy of the element, so assigning to it does not change the original array. For object arrays, you can modify the object's fields (since you have a reference copy), but you cannot replace the reference itself.
C is correct for primitive arrays. The for-each variable is a copy of the element, so assigning to it does not change the original array. For object arrays, you can modify the object's fields (since you have a reference copy), but you cannot replace the reference itself.
MCQ 10
What does break do inside a nested loop?
Answer: B
B is correct.
B is correct.
break exits only the innermost enclosing loop. The outer loop continues normally. To exit multiple loops, use labeled break.MCQ 11
What is the time complexity of this code?
for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { ... } }Answer: C
C is correct. The outer loop runs n times. For each outer iteration, the inner loop runs n times. Total: n * n = n^2 operations. This is quadratic time complexity.
C is correct. The outer loop runs n times. For each outer iteration, the inner loop runs n times. Total: n * n = n^2 operations. This is quadratic time complexity.
MCQ 12
How many iterations does this loop execute?
for (int i = 1; i < 1000; i *= 2) { ... }Answer: B
B is correct. i doubles each time: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512. The next value would be 1024, which is not < 1000. So 10 iterations. This is logarithmic growth: approximately log2(1000) = ~10.
B is correct. i doubles each time: 1, 2, 4, 8, 16, 32, 64, 128, 256, 512. The next value would be 1024, which is not < 1000. So 10 iterations. This is logarithmic growth: approximately log2(1000) = ~10.
MCQ 13
What is the output?
int x = 0; for (int i = 0; i < 3; i++) for (int j = 0; j <= i; j++) x++; System.out.println(x);Answer: B
B is correct. i=0: j runs 0 to 0 (1 increment). i=1: j runs 0 to 1 (2 increments). i=2: j runs 0 to 2 (3 increments). Total: 1 + 2 + 3 = 6.
B is correct. i=0: j runs 0 to 0 (1 increment). i=1: j runs 0 to 1 (2 increments). i=2: j runs 0 to 2 (3 increments). Total: 1 + 2 + 3 = 6.
MCQ 14
Which of the following is NOT a valid for loop in Java?
Answer: D
D is correct. In a for loop's initialization, you can declare multiple variables of the same type (option B). You cannot declare variables of different types (int and long) in the same initialization. The other options are all valid.
D is correct. In a for loop's initialization, you can declare multiple variables of the same type (option B). You cannot declare variables of different types (int and long) in the same initialization. The other options are all valid.
MCQ 15
What is the syntax for a do-while loop?
Answer: B
B is correct. The do-while loop syntax requires a semicolon after the while condition:
B is correct. The do-while loop syntax requires a semicolon after the while condition:
do { body } while (condition);.MCQ 16
How many times does the body of this loop execute?
int i = 10; while (i < 10) { i++; }Answer: A
A is correct. The condition
A is correct. The condition
10 < 10 is false from the start, so the while loop body never executes.MCQ 17
What is the output?
for (int i = 0; i < 5; i++) { if (i % 2 == 0) continue; System.out.print(i); }Answer: B
B is correct. When i is even (0, 2, 4), continue skips the print. When i is odd (1, 3), it prints. Output: 13.
B is correct. When i is even (0, 2, 4), continue skips the print. When i is odd (1, 3), it prints. Output: 13.
Coding Challenges
Challenge 1: Sum of Digits
EasyTake an integer N from the user and calculate the sum of its digits using a while loop. Example: 1234 -> 1+2+3+4 = 10.
Sample Input
Enter a number: 1234
Sample Output
Sum of digits: 10
Use % 10 to get the last digit and / 10 to remove it. Use while loop.
import java.util.Scanner;
public class SumDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int sum = 0;
int temp = n;
while (temp > 0) {
sum += temp % 10;
temp /= 10;
}
System.out.println("Sum of digits: " + sum);
sc.close();
}
}Challenge 2: Reverse a Number
EasyTake an integer and print its reverse. Example: 12345 -> 54321.
Sample Input
Enter a number: 12345
Sample Output
Reversed: 54321
Use a while loop with % 10 and / 10.
import java.util.Scanner;
public class ReverseNum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int reversed = 0;
while (n > 0) {
reversed = reversed * 10 + n % 10;
n /= 10;
}
System.out.println("Reversed: " + reversed);
sc.close();
}
}Challenge 3: Fibonacci Series
MediumPrint the first N Fibonacci numbers. Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, ...
Sample Input
Enter N: 8
Sample Output
0 1 1 2 3 5 8 13
Use a for loop. Track the previous two numbers.
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter N: ");
int n = sc.nextInt();
int a = 0, b = 1;
for (int i = 0; i < n; i++) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
System.out.println();
sc.close();
}
}Challenge 4: Prime Number Checker
MediumTake a number and determine if it is a prime number. Optimize: check divisors only up to the square root of N.
Sample Input
Enter a number: 29
Sample Output
29 is a prime number
Use a for loop up to Math.sqrt(n). Handle edge cases (0, 1, negative).
import java.util.Scanner;
public class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
if (n <= 1) {
System.out.println(n + " is not a prime number");
} else {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
System.out.println(n + (isPrime ? " is a prime number" : " is not a prime number"));
}
sc.close();
}
}Challenge 5: Number Guessing Game
MediumGenerate a random number between 1 and 100. Let the user guess until they get it right. Give hints (too high/too low) and count the number of attempts.
Sample Input
Guess: 50
Too high!
Guess: 25
Too low!
Guess: 37
Correct!
Sample Output
You guessed it in 3 attempts!
Use do-while loop. Use Math.random() or java.util.Random.
import java.util.Scanner;
import java.util.Random;
public class GuessGame {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int target = new Random().nextInt(100) + 1;
int guess, attempts = 0;
do {
System.out.print("Guess (1-100): ");
guess = sc.nextInt();
attempts++;
if (guess < target) System.out.println("Too low!");
else if (guess > target) System.out.println("Too high!");
else System.out.println("Correct! You guessed it in " + attempts + " attempts!");
} while (guess != target);
sc.close();
}
}Challenge 6: GCD Using Euclidean Algorithm
MediumFind the GCD (Greatest Common Divisor) of two numbers using the Euclidean algorithm with a while loop.
Sample Input
Enter two numbers: 48 18
Sample Output
GCD: 6
Use while loop: while (b != 0) { temp = b; b = a % b; a = temp; }
import java.util.Scanner;
public class GCD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter two numbers: ");
int a = sc.nextInt(), b = sc.nextInt();
int origA = a, origB = b;
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
System.out.println("GCD of " + origA + " and " + origB + ": " + a);
sc.close();
}
}Challenge 7: Armstrong Number Checker
HardCheck if a number is an Armstrong number. An N-digit number is Armstrong if the sum of its digits each raised to the power N equals the number itself. Example: 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153.
Sample Input
Enter a number: 153
Sample Output
153 is an Armstrong number
First count digits, then compute sum of powers.
import java.util.Scanner;
public class Armstrong {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int n = sc.nextInt();
int digits = String.valueOf(n).length();
int sum = 0, temp = n;
while (temp > 0) {
int d = temp % 10;
sum += Math.pow(d, digits);
temp /= 10;
}
System.out.println(n + (sum == n ? " is" : " is not") + " an Armstrong number");
sc.close();
}
}Challenge 8: Print All Prime Numbers in a Range
HardTake two numbers L and R from the user and print all prime numbers in the range [L, R] inclusive. Also print the count of primes found.
Sample Input
Enter range: 10 30
Sample Output
Primes: 11 13 17 19 23 29
Count: 6
Use nested loops: outer for range, inner for prime checking. Optimize with sqrt.
import java.util.Scanner;
public class PrimesInRange {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter range: ");
int l = sc.nextInt(), r = sc.nextInt();
int count = 0;
System.out.print("Primes: ");
for (int num = l; num <= r; num++) {
if (num <= 1) continue;
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) { isPrime = false; break; }
}
if (isPrime) {
System.out.print(num + " ");
count++;
}
}
System.out.println("\nCount: " + count);
sc.close();
}
}Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn Java with a live mentor?
Explore our Java Masterclass