Page 90 - TP_iPlus_V2.1_Class8
P. 90

i +  WRITING SOME MORE PROGRAMS

                  Till now, we have learned conditional, looping and jump statements of Java. We have also created
                  related programs in Java. Let us now create some other programs.
                  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++;
                                                                                               Output
                          }
                      }
                  }

                  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;
                              }
                                                                                        Output
                       }
                       System.out.println("The sum of all the odd numbers up to 10 is: " + sum);
                     }
                  }



                    88
                          iPlus (Ver. 2.1)-VIII
   85   86   87   88   89   90   91   92   93   94   95