Skip to main content

L04 - Part 2

Loops.java

public class Loops {
    public static void main(String[] args) {
        // sum the numbers from 1 to 5 using a for loop
        int sum = 0;
        for (int i = 0; i <= 5; i++) {
            sum = sum + i;
        }
        System.out.println("The sum of the numbers from 1 to 5 is " + sum);

        // sum the numbers from 1 to 10 using a while loop
        sum = 0;
        int i = 0;
        while (i < 10) {
            i = i + 1;
            sum = sum + i;
        }
        System.out.println("The sum of the numbers from 1 to 10 is " + sum);

        // sum the numbers from 1 to 15 using a do...while loop
        sum = 0;
        i = 0;
        do {
            i = i + 1;
            sum = sum + i;
        } while (i < 15);
        System.out.println("The sum of the numbers from 1 to 15 is " + sum);
    }
}