Welcome back everyone. In today’s article we will be looking at while loop and for loop in Java. We will explore while loop, do-while loop, for loop, nested for loop and for-each loop. We will also practice some real world problems. So, let’s get started!
Loops
Loops can execute a block of code as long as a specified condition is reached. Loops are handy because they save time, reduce errors, and they make code more readable.
Java While Loop
The while loop loops through a block of code as long as a specified condition is true:
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Note
Do not forget to increase the variable used in the condition (i++), otherwise the loop will never end!
Do you wonder why we used the letter i in the example above? It’s a counter variable and a common choice in simple loops because it’s short, traditional, and stands for ‘index’ or ‘iterator’.
Countdown Example
This example counts down from 3 to 1 and then displays “Happy New Year!!” at the end:
Example
int countdown = 3;
while (countdown > 0) {
System.out.println(countdown);
countdown--;
}
System.out.println("Happy New Year!!");
The Do/While Loop
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true. Then it will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
}
while (condition);
Note
The semicolon ; after the while condition is required!
The Do/While Example
The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:
Example
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
Note
Do not forget to increase the variable used in the condition (i++), otherwise the loop will never end!
Condition is False from the Start
In the example above, the condition i < 5 was true at the beginning, so the loop executed multiple times. But what if the condition is false right from the start?
In the example below, the variable i starts at 10, so the condition i < 5 is false immediately – yet the do/while loop still runs once:
Example
int i = 10;
do {
System.out.println("i is " + i);
i++;
} while (i < 5);
Summary
The do/while loop always runs at least once, even if the condition is already false. This is different from a regular while loop, which would skip the loop entirely if the condition is false at the start.
This behavior makes do/while useful when you want to ensure something happens at least once, like showing a message or asking for user input.
Real-Life Examples
To demonstrate a practical example of the while loop, we have created a simple “countdown” program:
Example
int countdown = 3;
while (countdown > 0) {
System.out.println(countdown);
countdown--;
}
System.out.println("Happy New Year!!");
To demonstrate a practical example of the while loop combined with an if else statement, let’s say we play a game of Yatzy:
Example
Print “Yatzy!” If the dice number is 6:
int dice = 1;
while (dice <= 6) {
if (dice < 6) {
System.out.println("No Yatzy.");
} else {
System.out.println("Yatzy!");
}
dice = dice + 1;
}
If the loop passes the values ranging from 1 to 5, it prints “No Yatzy”. Whenever it passes the value 6, it prints “Yatzy!”.
Java For Loop
When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop:
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Print Numbers
The example below will print the numbers 0 to 4:
Example
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Example Explained
- Statement 1 sets a variable before the loop starts:
int i = 0 - Statement 2 defines the condition for the loop to run:
i < 5. If the condition is true, the loop will run again; if it is false, the loop ends. - Statement 3 increases a value each time the code block has run:
i++
Print Even Numbers
This example prints even values between 0 and 10:
Example
for (int i = 0; i <= 10; i = i + 2) {
System.out.println(i);
}
Sum of Numbers
This example calculates the sum of numbers from 1 to 5:
Example
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum = sum + i;
}
System.out.println("Sum is " + sum);
Countdown
This example prints a countdown from 5 to 1:
Example
for (int i = 5; i > 0; i--) {
System.out.println(i);
}
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The “inner loop” will be executed one time for each iteration of the “outer loop”:
Example
// Outer loop
for (int i = 1; i <= 2; i++) {
System.out.println("Outer: " + i); // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; j++) {
System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)
}
}
Multiplication Table Example
This example uses nested loops to print a simple multiplication table (1 to 3):
Example
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.print(i * j + " ");
}
System.out.println();
}
1 2 3
2 4 6
3 6 9
Nested loops are useful when working with tables, matrices, or multi-dimensional data structures.
The for-each Loop
There is also a “for-each” loop, which is used exclusively to loop through elements in an array (or other data structures):
Syntax
for (type variableName : arrayName) {
// code block to be executed
}
The following example outputs all elements in the cars array, using a “for-each” loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Real Life Examples
To demonstrate a practical example of the for loop, let’s create a program that counts to 100 by tens:
Example
for (int i = 0; i <= 100; i += 10) {
System.out.println(i);
}
In this example, we create a program that only print even values between 0 and 10:
Example
for (int i = 0; i <= 10; i = i + 2) {
System.out.println(i);
}
And in this example, we create a program that prints the multiplication table for a specified number:
Example
int number = 2;
// Print the multiplication table for the number 2
for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}



Leave a Reply