Python Program to Find the Sum of Natural Numbers

Problem Description

Write a program that takes the number of terms and calculates the sum of the first N natural numbers.

Problem Solution

Natural numbers are all positive integers ranging from 1 to infinity. The sum of the first n natural numbers, for any number n, is defined as 1 + 2 + 3 + … + n.

1. Accept the number of natural numbers to sum and store it in a dedicated 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. The user is prompted to input the number of natural numbers required to compute the sum.
2. Initialize the sum variable to 0.
3. The while loop is used to find the sum of natural numbers and the number is decremented for each iteration.
4. Natural numbers are continuously added to the sum variable until the count reaches zero.
5. Once the count becomes zero, the program prints the total sum of the first N natural numbers.

advertisement
advertisement
Runtime Test Cases

Testcase 1: In this scenario, the user inputs the number “18” to calculate the sum of natural numbers.

Enter a number: 18
The sum of first n natural numbers is 171

Testcase 2: In this case, the user inputs the number “167” to calculate the sum of natural numbers.

Note: Join free Sanfoundry classes at Telegram or Youtube
Enter a number: 167
The sum of first n natural numbers is 14028

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

advertisement

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.