Monday 28 December 2020

Python Program to Find the Sum of First N Natural Numbers

 This is a Python Program to find the sum of first N Natural Numbers.

Problem Description

The program takes in the the number of terms and finds the sum of first N Natural Numbers.

Problem Solution

1. Take in the number of natural numbers to find the sum of and store it in a separate variable.
2. Initialize the sum variable to 0.
3. Use a while loop to find the sum of natural numbers and decrement the number for each iteration.
4. The numbers are added to the sum variable and this continues until the the value of the number is greater than 0.
5. Then the sum of first N natural numbers is printed.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the sum of first N Natural Numbers. The program output is also shown below.

n=int(input("Enter a number: "))
sum1 = 0
while(n > 0):
    sum1=sum1+n
    n=n-1
print("The sum of first n natural numbers is",sum1)
Program Explanation

1. User must enter the number of natural numbers to find the sum of.
2. The sum variable is initialized to 0.
3. The while loop is used to find the sum of natural numbers and the number is decremented for each iteration.
4. The numbers are added to the sum variable and this continues till the value of the variable is greater than 0.
5. When the value of the variable becomes lesser than 0, the total sum of N natural numbers is printed.

Runtime Test Cases
 
Case 1:
Enter a number: 18
The sum of first n natural numbers is 171
 
Case 2:
Enter a number: 167
The sum of first n natural numbers is 14028

No comments:

Post a Comment