Print all odd numbers between 1 to 100 in java [2 ways] - CY

Do you what to print all odd numbers between 1 and 100 ? Here you can learn 2 different approaches to write this program and proper explanation.

Display all odd numbers between 1 to 100 in java

Print all odd numbers between 1 to 100 in java [2 ways] - CY

Do you what to print all odd numbers between 1 and 100 ? Here you can learn 2 different approaches to write this program and proper explanation.

Approach:-1 " display odd numbers from 1 to 100 in java using for loop"

 
public class usingForLoop 

{

    public static void main(String[] args)

    {

     System.out.println("Odd numbers from 1 - 100 using for loop");

     

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

      {

        if(i % 2 != 0)

        {

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

        }

      }

      

    }

}


+
Explanation

You can see first I have filtered all the numbers from 1 to 100 using for loop.

Now using If statement I have checked, which numbers are not divisible by 0. I mean check for even or odd

Now simply I have printed the number which will satisfy the if condition i.e for odd number condition.

Output

display odd numbers from 1 to 100 in java using for loop

Approach:-2 "print all odd numbers between 1 and 100 using while loop"

 public class usingWhileLoop 

{

    public static void main(String[] args)

    {

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

      int num = 1;

      

      while(num <= 100)

      {

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

        num = num + 2;

      }

    }

} 

 
+
Explanation

In while loop I haven't use if statement to check the condition, here an another logic is applied. 

See if we add 2 to a odd number, then the result number will also be an odd number

  • Ex :- 3 is odd, now 3+2 = 5 , here 5 is also odd number. 

I have use this concept to print all the odd numbers from 1 to 100.

Output

print all odd numbers between 1 and 100 using while loop

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 ask me in the comment section. I will definitely answer your questions.

`

Post a Comment

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