Write a Java program to find the following sum of series:-
S=1-x^2/2+x^3/3-x^4/4........x^n/n
Answers
Question:-
- WAP to find the sum of following series
Code Language:-
- Java
Code:-
package Coder;
import java.util.*;
public class SerSum
{
public static void main (String ar [])
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter value of x");
int x=sc.nextInt();
System.out.println("Enter a limit");
int n=sc.nextInt();
double s=1;
for(int I=2;I<=n;I++){//Since we have stored the first term in variable 's' so loop will start from 2
{
if(I%2==0)
s=s-(Math.pow(x,I)/I);
else
s+=(Math.pow(x,I)/I);
}
}
System.out.println("Sum="+s);
}
}
Variable Description:-
- s:- to find the sum
- I:- Loop variable
Code Explanation:-
- The program accepts value of x and the number of terms from the user
- Then it runs a loop from 2 to 10 because we had already declared and initialised Sum variable 's' as 1. So the loop will run from second term
- Then it checks whether loop value is divisible by 2 or not (For more details, please refer to the "Note" section given below)
- If loop value is divisible by 2, it substract the new terms from the previously stored value of 's'.
- If Loop value is not divisible then it adds the new term to the previously stored value of 's'.
- Then the loop value gets updated with +1
- Once the loop value exceeds the limit, the loop terminates
- After this, the sum is displayed.
- Finally, the program terminates.
Note:-
- The even terms are negative and the odd terms are positive that's why 's' is initialized to 1 and the loop value starts from 2.
- Math.pow() returns a number raised to power another number. Example:-
Consider the attachment :
What have I done?
(i) I took input for "n" and "x".
(ii) Since every second element has a negative sign before, I used Math.pow() to adequate raise (-1) to the power to ensure the -ve sign before.
PS I hate the white background too.