Page 91 - iPro_trackGPT_V5_Class8
P. 91

Program 1: Write a Java program to print all the even numbers between 1 and N by using the
                 while loop. The value of N should be taken from the user as input.

                 public class Program1
                 {
                     public static void main(int N)

                     {
                         int i = 1;

                         System.out.println("Even numbers between 1 to "+ N+ " are:");
                         while (i <= N)
                         {

                             if(i%2==0)
                             {

                             System.out.println(i);
                             }
                             i++;

                         }
                     }

                 }

                 In the preceding program, we need to provide the value of the variable N from runtime.

                 Program 2: Write a Java program to print the sum of all the odd numbers up to 10 by using the
                 for loop.
                 public class Program2
                 {

                    public static void main(String args[])
                    {

                         int i, sum=0;
                        for(i=1; i<=10; i++)
                      {

                             if(i%2 != 0)
                             {

                                  sum+=i;
                             }
                      }

                      System.out.println("The sum of all the odd numbers up to 10 is: " + sum);
                    }

                 }


                                                                Conditional, Looping and Jump Statements in Java  89
   86   87   88   89   90   91   92   93   94   95   96