Computer Science, asked by ShivHalvawala, 5 months ago

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

Answered by BrainlyProgrammer
9

Question:-

  • WAP to find the sum of following series

  \sf S=1 -  \dfrac{ {x}^{2} }{2}  +  \dfrac{ {x}^{3} }{3}  -   \dfrac{ {x}^{4} }{4}  + .......  \dfrac{ {x}^{n} }{n}

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:-

  1. The program accepts value of x and the number of terms from the user
  2. 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
  3. Then it checks whether loop value is divisible by 2 or not (For more details, please refer to the "Note" section given below)
  4. If loop value is divisible by 2, it substract the new terms from the previously stored value of 's'.
  5. If Loop value is not divisible then it adds the new term to the previously stored value of 's'.
  6. Then the loop value gets updated with +1
  7. Once the loop value exceeds the limit, the loop terminates
  8. After this, the sum is displayed.
  9. 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:-  \sf {(n)}^{x}
Attachments:
Answered by allysia
4

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.

Attachments:
Similar questions