Simple Loop - Display All Numbers From 1 To 100

Below is a very simple example that shows how to use simple loop. We will display all numbers from 1 to 100 in Java.

Display All Numbers From 1 To 100 Using For Loop

Below is a simple program in Java that uses for loop to display all numbers between 1 and 100 inclusive:

/**
 * A simple program that outputs all numbers from 1 to 10.
 */
public class ExampleLoopProgram {
    public static void main(String[] args) {
        for (int i=1; i<=100; i++) {
            System.out.println(i);
        }
    }
}

So what this does is that i is initialized with the value 1. If the value meets the condition (i<=100), which is yes because i has initial value 1, will go to the block statement that displays i. So on first iteration, 1 is displayed. Then i is incremented due to the i++ statement in the for loop. So the next time, i will have the value of 2, and then 2 is displayed. This goes on until i becomes 101 which does not meet the condition that i<=100, hence the program will exit at 101, with 100 being the last displayed output.

Display All Numbers From 1 To 100 Using While Loop

Below is another example on how to display the numbers between 1 and 100 inclusive using while loop:
/**
 * A simple program that outputs all numbers from 1 to 10.
 */
public class ExampleLoopProgram {
    public static void main(String[] args) {
        int i = 1;
        while (i<=100) {
            System.out.println(i);
            i++;
        }
    }
}
The explanation is the same as the for loop, we just did all what for loop does ourselves through explicit code.