Monday 28 December 2020

Python Program to Find the Sum of the Series: 1 + 1/2 + 1/3 + ….. + 1/N

 This is a Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N.

Problem Description

The program takes in the the number of terms and finds the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N.

Problem Solution

1. Take in the number of terms to find the sum of the series for.
2. Initialize the sum variable to 0.
3. Use a for loop ranging from 1 to the number and find the sum of the series.
4. Print the sum of the series after rounding it off to two decimal places.
5. Exit.

Program/Source Code

Here is source code of the Python Program to find the sum of series: 1 + 1/2 + 1/3 + ….. + 1/N. The program output is also shown below.

n=int(input("Enter the number of terms: "))
sum1=0
for i in range(1,n+1):
    sum1=sum1+(1/i)
print("The sum of series is",round(sum1,2))
Program Explanation

1. User must enter the number of terms to find the sum of.
2. The sum variable is initialized to 0.
3. The for loop is used to find the sum of the series and the number is incremented for each iteration.
4. The numbers are added to the sum variable and this continues till the value of i reaches the number of terms.
5. Then the sum of the series is printed.

Runtime Test Cases
 
Case 1:
Enter the number of terms: 7
The sum of series is 2.59
 
Case 2:
Enter the number of terms: 15
The sum of series is 3.32

No comments:

Post a Comment