Page 224 - ComputerScience_Class_11
P. 224

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(String args[])

                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;
                29                  case 'b': System.out.println("Enter n  term");
                                                                                  th
                30                      n=sc.nextInt();






                  222  Touchpad Computer Science (Ver. 3.0)-XI
   219   220   221   222   223   224   225   226   227   228   229