print first 10 natural number in java( 2 approaches)
In this article you can learn how to write java program to print first 10 natural numbers with 2 different approaches.
Approach:-1 "print natural number in java using for loop"
public class usingForLoop
{
public static void main(String[] args)
{
for(int i = 1; i <= 10; i++)
{
System.out.print(i+" ");
}
}
}
In the for loop, loop is started from 1 and it will go upto 10 and each iteration the value of i is incrementing by 1.
So for first iteration it will print 1 and then in 2nd iteration the value of i will be incremented and become 2 and will printed.
Like this all 10 natural numbers will displayed in the output screen.
Output
Approach:-2 "display first 10 natural number in java using while loop"
public class usingWhileLoop
{
public static void main(String[] args)
{
int n = 1;
System.out.println("using while loop");
while(n < 11)
{
System.out.print(n + " ");
n++;
}
}
}
In while loop the logic remain same but here we have to declare the variables outside of the loop and we have to increament the value inside the loop.