Iteration is a fundamental concept in programming that allows us to repeat a block of code multiple times. This is incredibly useful when you need to perform the same action over and over again without writing the same code repeatedly.
In Java, we commonly use two types of loops for iteration:
for
loop
while
loop
for
LoopThe for
loop is used when you know in advance how many times you want to execute a statement or a block of statements.
for
Loopfor (initialization; condition; update) {
// statements
}
Initialization: This is where you initialize the loop control variable.
Condition: The loop runs as long as this condition is true.
Update: This updates the loop control variable after each iteration.
for
Loopfor (int i = 0; i < 5; i++) {
System.out.println("This is iteration number: " + i);
}
Explanation:
The loop control variable i
is initialized to 0.
The condition i < 5
is checked before each iteration.
The loop prints the current iteration number.
After each iteration, i
is incremented by 1.
while
LoopThe while
loop is used when you want to repeat a block of code as long as a condition is true, but you don't necessarily know in advance how many times the loop will run.
while
Loopwhile (condition) {
// statements
}
Condition: The loop runs as long as this condition is true.
while
Loopint count = 0;
while (count < 5) {
System.out.println("Count is: " + count);
count++;
}
Explanation:
The loop runs as long as count
is less than 5.
The current value of count
is printed.
After each iteration, count
is incremented by 1.
Imagine you are preparing a batch of cookies. You need to mix the dough for 5 minutes. You can use a loop to represent this repetitive action in code:
for
Loopfor (int minute = 1; minute <= 5; minute++) {
System.out.println("Mixing dough... Minute: " + minute);
}
In this example, the loop prints a message for each minute of mixing the dough, from minute 1 to minute 5.
Here’s a full Java program that demonstrates both for
and while
loops. This program prints the numbers from 1 to 5 using both types of loops.
public class LoopDemo {
public static void main(String[] args) {
// Using a for loop to print numbers from 1 to 5
System.out.println("Using for loop:");
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// Using a while loop to print numbers from 1 to 5
System.out.println("Using while loop:");
int count = 1;
while (count <= 5) {
System.out.println(count);
count++;
}
}
}
Explanation:
The for
loop runs from i = 1
to i <= 5
, printing each number.
The while
loop runs from count = 1
to count <= 5
, printing each number.
Write a program that prints all even numbers from 1 to 20 using a for
loop.
2
4
6
8
10
12
14
16
18
20
Use the modulus operator %
to check if a number is even. (number % 2 == 0
)
By understanding and practicing these iteration concepts, you'll be able to handle repetitive tasks in your programs efficiently!