Home Tutorial Java Core Find sum of series

 
 

Share on Google+Share on Google+
Find sum of series
Posted on: June 16, 2010 at 12:00 AM
Advertisement
This section illustrates you how to find the sum of n terms of the series using recursion.

Find sum of series

This section illustrates you how to find the sum of n terms of the series using recursion. For this purpose, we have created a recursive function that takes the parameter 'n' up to which the sum of the series is to be determined. Series is:

1+1/2 + 1/3 + 1/4 +................1/n.

Here is the code:

import java.util.*;

public class SumOfSeries {

	public static double sum(int n) {
		if (n == 1)
			return 1.0;
		return sum(n - 1) + 1.0 / n;
	}

	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);
		System.out.print("Enter number of terms :");
		int num = input.nextInt();
		System.out.println(sum(num));
	}
}

Output:

Enter number of terms: 5
2.2833333333333333
Advertisement

Related Tags for Find sum of series:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 16, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com