Write a program to find the sum of the following series:
1 - 2^1 + 3^2 - 4^3 + 5^4- ... upto n terms
BrainlyProgrammer:
which language shall this question should be answered?
Answers
Answered by
2
Required Answer:-
Question:
Write a program to find out the sum of the following series.
1 - 2¹ + 3² - 4³ + 5⁴. . . . . . .
Solution:
Here is the program.
import java.util.*;
public class Sum {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter limit - ");
int n=sc.nextInt();
double s=0.0;
for(int i=1;i<=n;i++) {
double x=Math.pow(i, i-1);
if(i%2==1)
s+=x;
else
s-=x;
}
System.out.println("Sum is: "+s);
sc.close();
}
}
Explanation:
- Nth term of the series is in the form of n^(n - 1). For example, 1 = 1⁰, 2 = 2¹ and so on. First term is added to the sum while the next term is subtracted from it. We have created a variable x that contains the nth term of the series. If the value of 'i' is odd, then it adds the value of x to the sum or else, it subtracts the value from the sum.
Output is attached.
Attachments:
Similar questions