Java Program to print first n Integers

In this program let us create a simple "PrintIntegers" program to print first n integers on the console based on user input.

Program

import java.util.*;
class PrintIntegers
{
	public static void main(String[] args)
	{
		Scanner sc = new Scanner(System.in);
		System.out.println("Enter the value of n");
		int n = sc.nextInt();
		System.out.println("Generating the list from 1 to " + n);
		for(int i = 1; i <= n; i++)
			System.out.println(i);
	}
}

Let us understand the program by breaking into simple parts:

  1. public class PrintIntegers: Any Java program starts with a class, in this case the class name is PrintIntegers
  2. public static void main(String[] args): main is the entry point for any Java program.
  3. Scanner sc = new Scanner(System.in); : System.in is passed as a parameter in Scanner class. This creates an object of Scanner class which is defined in java. util. scanner package. Scanner class tells the java compiler that system input will be provided through console(keyboard).
  4. System.out.println("Enter the value of n"); : Prompts the user to enter the value of n.
  5. int n = sc.nextInt(); : The nextInt() method of Java Scanner class is used to scan the next token of the input as an int. The value of n entered by the user is stored in the variable n
  6. System.out.println("Generating the list from 1 to " + n); : Displays the message to user
  7. for(int i = 1; i <= n; i++) : for loop iterates starting from i=1 to n (value entered by user), by incrementing i by 1
  8. System.out.println(i);: System.out.println prints the value of i after each iteration.

Output

Enter the value of n
7
Generating the list from 1 to 7
1
2
3
4
5
6
7

Tags: