AAP-2.K Write and determine the result or side effect of iteration statements

What is Iteration?

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.

Types of Iteration in Java

In Java, we commonly use two types of loops for iteration:

  1. for loop

  2. while loop

The for Loop

The for loop is used when you know in advance how many times you want to execute a statement or a block of statements.

Syntax of for Loop

for (initialization; condition; update) {
    // statements
}

Example of for Loop

for (int i = 0; i < 5; i++) {
    System.out.println("This is iteration number: " + i);
}

Explanation:

The while Loop

The 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.

Syntax of while Loop

while (condition) {
    // statements
}

Example of while Loop

int count = 0;
while (count < 5) {
    System.out.println("Count is: " + count);
    count++;
}

Explanation:

Real-World Example

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 (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.

Full Program Demonstrating Iteration

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:

Programming Problem

Problem: Print Even Numbers

Write a program that prints all even numbers from 1 to 20 using a for loop.

Example Output

2
4
6
8
10
12
14
16
18
20

Hints

By understanding and practicing these iteration concepts, you'll be able to handle repetitive tasks in your programs efficiently!