for loop in java

This program explains how to print sequence of number from 1 to a given input number using for loop.

Program

import java.io.*;
import java.util.*;

public class PrintNumberUsingLoop {
    public static void main(String[] args) {

        int number;
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter the number");
        number = scanner.nextInt();
        System.out.println("Result:");
        for (int i = 1; i <= number; i++) {
            System.out.println(i);
        }
    }
}

Output

Enter the number
5
Result
1
2
3
4
5

Explanation

  • Declare a variable with name 'number'.
  • Create an object for Scanner to get input from user in the console.
  • Print the message "Enter the number".
  • Get the input as integer type using nextInt() fuction of scanner object.
  • Initialize the variable i to 1 and check the condition whether i is greater than or equal to the given number.
  • Increment the value of i by 1 for each iteration in the for loop. When the condition 'i<=number' doesn't satisfy it will exit the loop.

Most Read