Expression Evaluation: In the Mini project 7th module is to evaluate the expression y = x + x^2+……..+x^n. Rita allotted this function to Malini. Collect and display the values returned by the called function. Test your program and report the results obtained.
Help Malini to write a program to evaluate the expression?
Get the value of x and n from the user as input
Use the following function:
int calculate(int x,int n)
where the first argument corresponds to the value of x and second corresponds to n respectively.
Sample Input and Output :
Enter the value of x
2
Enter the value of n
3
The result is
14
Solution
import java.util.*;
import static java.lang.Math.*;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the value of x");
int x = in.nextInt();
System.out.println("Enter the value of n");
int n = in.nextInt();
//sauravhathi
System.out.println("The result is\n"+calculate(x, n));
}
public static int calculate(int x, int n) {
int sum = 0;
for (int i = 1; i <= n; i++)
{
sum = sum + (int)pow(x, i);
}
return sum;
}
}
Happy Learning – If you require any further information, feel free to contact me.