Page 176 - computer science (868) class 11
P. 176

Program 10    Write a Java program to find the sum or print the given series as per the user’s choice.
                              a.  Sum of the series
                                s = 1 – 4 + 9 – 16 + ………… to n terms
                              b.  Print the series
                                1, 11, 111, 1111, …….… to n terms

                1       import java.util.*;
                2       class series

                3       {
                4           public static void main()

                5           {
                6               Scanner sc= new Scanner(System.in);

                7               int ch, s=0, n, i;
                8               System.out.println("a. s = 1 – 4 + 9 – 16 + ………… to n terms");

                9               System.out.println("b. 1, 11, 111, 1111, …….…. to n terms");
                10              System.out.println("Enter your choice ");

                11              ch=sc.next().charAt(0);
                12              switch(ch)

                13              {
                14                  case 'a': System.out.println("Enter n  term ");
                                                                                  th
                15                      n=sc.nextInt();
                16                      for(i=1; i<=n; i++)

                17                      {
                18                          if(i%2==0)

                19                          {
                20                              s=s-(i*i);

                21                          }
                22                          else
                23                          {

                24                              s=s+(i*i);

                25                          }
                26                      }
                27                      System.out.println("Sum = " +s);

                28                      break;
                                                                                  th
                29                  case 'b': System.out.println("Enter n  term");
                30                      n=sc.nextInt();



                174174  Touchpad Computer Science-XI
   171   172   173   174   175   176   177   178   179   180   181