To print numbers from 1 to N, we need to read the value of N by the user and then run a loop (we are using for loop here), logic to print numbers:
- First, we are creating an object named scanner of Scanner class to read the input.
- Declared a variable named n to store the value, given by the user, to read the input – we are using scanner.nextInt() – Here, nextInt() is the method of Scanner class, that will read an integer value.
- Then, using for loop from 1 to N to print the numbers from 1 to N.
Example:
Input:
Enter the value of N: 15
Numbers from 1 to 15
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Program to print the number from 1 to N using for loop in java
Output