Write a programt print the sum of the series s=1-2+3-4+5+6+7...n
Answers
Answer:
import java .util.*;
class series
{
public static void main()
{
Scanner sc= new Scanner(System.in);
System.out.println("enter an integer ");
int n = sc.nextInt();
int s=0;
for(int i=1; i<=n; i++)
{
s=s+i;
}
System.out.println("sum is"+ s);
}
}
Explanation:
Question:-
Write a program to print the sum of the series.
S=1-2+3-4+5-6+....N
Code:-
import java.util.*;
class Series
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the total number of terms for series sum: ");
int n=sc.nextInt();
int s=0;
for(int j=1;j<=n;j++)
s+=(j%2!=0)?j:-j;
System.out.println("Sum is: "+s);
}
}