Page 87 - iPlus_Ver_2.0_class_8
P. 87

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

                    }
                 }


                                                                                                                  85
                                                              Conditional, Looping and Jumping Statements in Java
   82   83   84   85   86   87   88   89   90   91   92