Positive whole numbers are called Natural numbers. In this Java Program, we are trying to print all the natural numbers using a while loop starting from 1 to n. Here n is the endpoint decided at runtime which will be given by the user.
Steps of Program
- We are using a ‘scanner’ to take input for the number.
- We need to iterate from the number one by one as natural numbers are positive whole numbers. For eg .. 1,2,3,4,5,6.
- After iterating and printing the number once we increment it by 1 and repeat the process till the while loop condition is met.
Note: Some mathematicians consider 0 as a natural number some don’t.
Java Program to print natural number from 1 to n using while loop
import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Print Natural Numebr Program in Java:");
System.out.println("Enter Value till the Natural numbers to be printed :");
int n = sc.nextInt();
int i = 1; //Natural numbers starting from 1
System.out.println("Natural number till "+n+ " are :");
while(i<=n) {
System.out.println(i);
i++;
}
sc.close();
}
}
Output
Print Natural Numebr Program in Java:
Enter Value till the Natural numbers to be printed :
12
Natural number till 12 are :
1
2
3
4
5
6
7
8
9
10
11
12