Friday 16 June 2017

Java Code to compute the sums for the first n terms.

Problem:

Develop an algorithm to compute the sums for the first n terms of the following series:
  a. s = 1+2+3+.......
  b. s = 1+3+5+.......
  c. s = 2+4+6+......
  d. s = 1+1/2+1/3+.....

Solution:

package com.myprograms;

import java.util.Scanner;

//This class is defined to find the sum of following series
//1. s = 1+2+3+.....
//2. s = 1+3+5+.....
//3. s = 2+4+6+.....
//4. s = 1+1/2+1/3+...
public class SunOfFirstNTerms {

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 series : ");
n = s.nextInt();
findTheSumOfSequenceNumbers();
findTheSumOfOddNumbers();
findTheSumOfEvenNumbers();
findTheSumOfReciprocals();

s.close();
}

private static void findTheSumOfSequenceNumbers(){
int sum = 0;
for(int i = 1; i<=n; i++){
sum = sum + i;
}
System.out.println("The sum of 1+2+3+... is: " + sum);
}

private static void findTheSumOfOddNumbers(){
int sum = 0;
for(int i = 1; i<=n; i=i+2){
sum = sum + i;
}
System.out.println("The sum of 1+3+5+... is: " + sum);

}

private static void findTheSumOfEvenNumbers(){

int sum = 0;
for(int i = 2; i<=n; i=i+2){
sum = sum + i;
}
System.out.println("The sum of 2+4+6+... is: " + sum);
}

private static void findTheSumOfReciprocals(){
double sum = 1.0;
for(int i = 2; i<=n; i++){
sum = sum + (1.0/i);
}
System.out.println("The sum of 1+1/2+1/3+... is: " + sum);

}
}


Output:

Enter the No. of terms in series :
10
The sum of 1+2+3+... is: 55
The sum of 1+3+5+... is: 25
The sum of 2+4+6+... is: 30
The sum of 1+1/2+1/3+... is: 2.9289682539682538


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...