Sunday 18 June 2017

Java Code to compute the sum of the first n terms of the series 1-3+5-7+9...

Problem:

Develop an algorithm to compute the sum of the first n terms of the series 1-3+5-7+9....

Solution:

package com.myprograms;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class SumOfFirstNTermsOfTheSeries {

static int n = 0;

public static void main(String[] args) {

Scanner s = new Scanner(System.in);
System.out.println("Enter the No. of terms in sequence : ");
n = s.nextInt();
findTheSumOfTheSequence();
s.close();
}

private static void findTheSumOfTheSequence(){
int sum = 0;
List<Integer> series  = new ArrayList<Integer>();
series.add(1);
for(int i = 0; i<n-1; i++){
series.add(series.get(i) + 2);
if((i%2) != 0){
series.set(i, -series.get(i));
}
else {
series.set(i, series.get(i));
}
}
for(Integer k: series){
sum = sum + k;
}
System.out.println("the series is: " + series);

System.out.println("The series sum is: " + sum);
}
}


Output:
Enter the No. of terms in sequence :
5
the series is: [1, -3, 5, -7, 9]
The series sum is: 5

Enter the No. of terms in sequence : 
10
the series is: [1, -3, 5, -7, 9, -11, 13, -15, 17, 19]
The series sum is: 28

No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...