Find sum of series


 

Find sum of series

This section illustrates you how to find the sum of n terms of the series using recursion.

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

Ads