Write a program that takes the number of terms and calculates the sum of the first N natural numbers.
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.
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)
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.
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.
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.
- Apply for Programming Internship
- Check Information Technology Books
- Check Python Books
- Practice Programming MCQs
- Apply for Python Internship