Advertisements
Advertisements
प्रश्न
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 sum of the series |
| Member functions/methods: | |
| 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 call( ). Define the main() function to create an object and call the member function accordingly to enable the task.
कोड लेखन
Advertisements
उत्तर
import java.util*;
public class CalSeries
{
int x,n,sum;
public CalSeries()
{
x=0;
n=0;
sum=1;
}
public void input()
{
Scanner in = new Scanner(System.in);
System.out.println(“Enter the value of x”);
x=innextInt();
System.out.println(“Enter the value of n");
n=in.nextInt();
}
public int power(int p,int q)
{
if (q==1)
return x;
else return x*power(x,q-1);
}
public void cal()
{
for(int i=1;i<=n;i++)
{
int r=power(x,i);
sum+=r;
}
System.out.println(“Sum of the series is :"+
sum);
}
public static void main(String args[])
{
CalSeries obj=new CalSeries();
obj.input();
obj.cal();
}
}shaalaa.com
क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
