Share on Google+Share on Google+

Find sum of series

Ads
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

Advertisements

Posted on: June 16, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial 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.