print first 10 natural number in java with 2 approaches | CY

In this article you can learn how to write java program to print first 10 natural numbers with 2 different approaches. code yourself - codeYourslf
5 min read

print first 10 natural number in java( 2 approaches)

print first 10 natural number in java with 2 approaches | CY

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+" ");

      }

    }

}
+
Explanation

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

print first 10 natural number in java with 2 approaches | CY

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++;

      }

    }

} 


 
+
Explanation

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.

Output

print first 10 natural number in java with 2 approaches | CY

Hey if you learn something new from this article please share with your friends .
And if you have any questions or any doubt, feel free to write it on the comment below 👇. I will definitely answer to you.

`

You may like these posts

1 comment

  1. second ago
    Please provide your review
Hey Please 👏, feel free to share your opinion 🌍