Display even numbers between 1 to 100 in java [in 2 ways]-CY

In this article you can learn to write a java program that will display all the even numbers between 1 and 100 with 2 different approaches. CY

Display all even  numbers between 1 to 100 in java

Display even numbers between 1 to 100 in java [in 2 ways]-CY

In this article you can learn to write a java program that will display all the even numbers between 1 and 100 with 2 different approaches.

Approach:-1 "print all even numbers between 1 and 100 in java using for loop"

 public class usingForLoop {

    public static void main(String[] args){

      System.out.println("Using For Loop");

      for(int i = 1; i <= 100; i++)

      {

        if(i % 2 == 0)

        {

          System.out.print(i + " ");

        }

      }

    }

} 

 
+
Explanation

In this program I have used for loop. Here I have fetched all the numbers from 1 to 100.

And in if statement, I have checked which numbers are even using modulus operator (%)

Now those numbers satisfy the even numbers condition i.e i % 2 == 0, has been printed.

Output

print all even numbers between 1 and 100 in java

Approach:-2 "display even numbers between 1 and 100 in java using while loop"

 public class usingWhileLoop {

    public static void main(String[] args){

      System.out.println("Using while loop");

      int num = 2;

      

      while(num <= 100)

      {

        System.out.print(num + " ");

        num = num + 2;

      }

    }

} 
+
Explanation

In this approach I haven't use if condition, here I have simply added 2 to each numbers

See if you add 2 to an even number, then the result number will be an even number. 

  • Ex:- 4 is even, now 4 + 2 = 6, here 6 also even number. 

Here I have started the loop from 2 and at each iteration I am adding 2 to the new number.

Output

print all even numbers between 1 and 100 in java

  • - print all the ODD numbers between 1 to 100 using 2 approaches :- click 
Hey if you learn something new from the article, then please share with your friends.

And if you have any questions or any query then please ask me in the comment section. I will definitely answer to you.
`

إرسال تعليق

Hey Please 👏, feel free to share your opinion 🌍
© codeYourslf. All rights reserved. Distributed by Pixabin