Page 310 - CA_Blue( J )_Class10
P. 310

To calculate sum of the following series:
                Program 2     s=1 + 4 + 9 + 16 + ..... + n terms
                              Create a class series, which will contain the following members:
                              Data Members
                              int n                :  To store the nth term.
                              Member Methods
                              series()             :  Constructor to initialize n.
                              void input()         :  Input a number n for the series(1+...+n).
                              int compute( )       :  To calculate the sum of the series and store it in s.
                              void display( )      :  Calls the method compute() and prints the sum.

                 1  import java.util.*;

                 2  class series
                 3  {
                 4      int n;

                 5      series()

                 6      {
                 7          n=0;

                 8      }
                 9      void input()

                10      {
                11          Scanner sc=new Scanner(System.in);

                12          System.out.println("Enter nth term");
                13          n=sc.nextInt();

                14      }
                15      int compute()
                16      {

                17          int i,s=0;

                18          for(i=1;i<=n;i++)
                19          {
                20              s=s+(i*i);

                21          }
                22          return s;

                23      }
                24      void display()

                25      {
                26          int sum=compute();

                27          System.out.println("The result is : "+sum);



                308308  Touchpad Computer Applications-X
   305   306   307   308   309   310   311   312   313   314   315