Java Day 5: Loops

Goal of this Day

Today you will learn:

By the end, you will be able to repeat tasks automatically using loops.

Step 1: for Loop

The for loop is used when you know how many times to repeat something.


for(int i = 1; i <= 5; i++) {
    System.out.println("Number: " + i);
}

Explanation:

Step 2: while Loop

The while loop runs as long as a condition is true.


int i = 1;

while(i <= 5) {
    System.out.println("Number: " + i);
    i++;
}

Step 3: do-while Loop

The do-while loop always runs at least once.


int i = 1;

do {
    System.out.println("Number: " + i);
    i++;
} while(i <= 5);

Step 4: break and continue

break

Stops the loop completely.


for(int i = 1; i <= 10; i++) {
    if(i == 5) {
        break;
    }
    System.out.println(i);
}

continue

Skips the current iteration.


for(int i = 1; i <= 5; i++) {
    if(i == 3) {
        continue;
    }
    System.out.println(i);
}

Practice


for(int i = 1; i <= 5; i++) {
    System.out.println("Number: " + i);
}

Exercise

Print all even numbers from 1 to 50 using a loop.

Steps:

Example:


public class EvenNumbers {
    public static void main(String[] args) {
        for(int i = 1; i <= 50; i++) {
            if(i % 2 == 0) {
                System.out.println(i);
            }
        }
    }
}