write a program in java to find the sum of the series 3-5+8-12+17.......upto n terms.
Answers
Series Summation Program in Java
We have a series whose sum we have to find by writing a program in Java. Let us analyze the series to understand the pattern.
Consider just the absolute value of the terms:
3, 5, 8, 12, 17, ...
The pattern lies in their difference:
As we can see, the difference gets increased by 1 with each term.
So, while writing the program, we must include a variable which will contain the value of Sum, then we should have a variable which would contain the value of each term as we progress through a loop, and finally we should also have a variable by which we would increment the terms. The value of this increment variable would itself increment with each iteration of the loop.
Here is a Java program implementing everything and calculating the Series Sum:
import java.util.Scanner; //Importing Scanner
public class Brainly //Creating class
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in); //Creating Scanner object
System.out.print("Enter number of terms: "); //Asking for user input
int n = sc.nextInt(); //Checking user input
int Sum = 0; //Creating and Initialising Sum to 0
int term = 3; //The value of the current term
int incrementValue = 2; //The increment value by which term is to be incremented
for(int i=0;i<n;i++) //Setting a loop to run n times
{
if(i%2==0) //If i is even, term is added to Sum
{
Sum = Sum + term;
}
else //If i is odd, term is subtracted from Sum
{
Sum = Sum - term;
}
term = term + incrementValue; //Incrementing term by required value
incrementValue++; //Incrementing this variable for next iteration
}
System.out.println("Series Sum = "+Sum); //Printing Sum
}
}