The following program demonstrates how to Compute the Sum of a Series in Java.

In this program, we have two input numbers: n1, and n2. While the number n2 indicates an option that takes a value of either 1 or 2.

When n2=1, the series sum will be computed as follows.

sum=n1-(n1-1)+(n1-2)-(n1-3)+(n1-4)…………..1

Similarly, for n2=2, we want to compute the sum as follows:

sum=n1+(n1-1)-(n1-2)+(n1-3)-(n1-4)…………1

The following code implements the above logic.

public class Sequences
{
	public static void main(String[] args)
	{
		System.out.println(secondSequence(6, 1));
		System.out.println(secondSequence(6, 2));
	}
	public static int secondSequence(int input1, int input2)
	{
		int ans=input1, n, t, x1=-1, x2=1;
		n=input1;
		
		if(input2==1)
		{
			for(int i=1;i<=n;i++)
			{
				t=n-i;
				t=t*x1;
				ans+=t;
				x1=x1*(-1);		
			}
		}
		if(input2==2)
		{
			for(int i=1;i<=n;i++)
			{
				t=n-i;
				t=t*x2;
				ans+=t;
				x2=x2*(-1);		
			}
		}
		return ans;
	}
}

Output

A Program to Compute the Sum of a Series in Java
A Program to Compute the Sum of a Series in Java

Further Reading

Java Practice Exercise

programmingempire

Princites