Print the series : S= a- a^3+ a^5 - a^7......... In java
Answers
Series Sum - Java
We can calculate the Sum of series till n terms. We need to take user input for two values:
- Value of a
- Number of terms n
Using these two values we can calculate the Series Sum. We would initialize a Sum variable to 0 and then run a loop from n times to get the Sum of n terms.
We need to first generalize the Sum in a Mathematical Form to be able to put it in the program.
Here's how we do it:
We can easily put this in a loop to get the required Sum. For powers, we use the Math.pow() function.
import java.util.Scanner; //Importing Scanner
public class SeriesSum //Creating Class
{
public static void main(String[] args) //The main function
{
Scanner sc = new Scanner(System.in); //Creating Scanner Object
//Take User Input for 'a'
System.out.print("Enter the value of 'a': ");
double a = sc.nextDouble();
//Take User Input for number of terms (n)
System.out.print("Enter the number of terms: ");
int n = sc.nextInt();
double Sum = 0; //Initialise Sum to 0
for(int i=0;i<n;i++) //Run a loop n times
{
//Add Terms to Sum
Sum += Math.pow(-1,i) * Math.pow(a,(2*i+1));
}
//Print Final Series Sum
System.out.println("The Series Sum is: "+Sum);
}
}
Answer:
Explanation:
import java.util.Scanner; //Importing Scanner
public class SeriesSum //Creating Class
{
public static void main(String[] args) //The main function
{
Scanner sc = new Scanner(System.in); //Creating Scanner Object
//Take User Input for 'a'
System.out.print("Enter the value of 'a': ");
double a = sc.nextDouble();
//Take User Input for number of terms (n)
System.out.print("Enter the number of terms: ");
int n = sc.nextInt();
double Sum = 0; //Initialise Sum to 0
for(int i=0;i<n;i++) //Run a loop n times
{
//Add Terms to Sum
Sum += Math.pow(-1,i) * Math.pow(a,(2*i+1));
}
//Print Final Series Sum
System.out.println("The Series Sum is: "+Sum);
}
}