Calculate Series ISC Computer Science 2022 Semester 2 Theory

A class CalSeries has been defined to calculate the sum of the series:

sum = 1 + x + x2 + x3 + ... + xn

Some of the members of the class are given below:

Class name: CalSeries

Data members/instance variables:
x: integer to store the value of x
n: integer to store the value of n
sum: integer to store the sum of the series

Methods/Member functions:
CalSeries(): default constructor
void input(): to accept the values of x and n
int power(int p, int q): return the power of p raised to q (pq) using recursive technique
void cal(): calculates the sum of the series by invoking the method power() and displays the result with an appropriate message

Specify the class CalSeries, giving details of the constructor, void input(), int power(int, int) and void cal(). Define the main() function to create an object and call the member functions accordingly to enable the task.

import java.util.Scanner;
class CalSeries{
    int x;
    int n;
    int sum;
    public CalSeries(){
        x = 0;
        n = 0;
        sum = 0;
    }
    public void input(){
        Scanner in = new Scanner(System.in);
        System.out.print("n = ");
        n = Integer.parseInt(in.nextLine());
        System.out.print("x = ");
        x = Integer.parseInt(in.nextLine());
    }
    public int power(int p, int q){
        if(q == 0)
            return 1;
        return p * power(p, q - 1);
    }
    public void cal(){
        for(int i = 0; i <= n; i++)
            sum += power(x, i);
        System.out.println("Sum = " + sum);
    }
    public static void main(String[] args){
        CalSeries obj = new CalSeries();
        obj.input();
        obj.cal();
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory