Program to Find the Sum of Natural Numbers

Python Program to Find the Sum of Natural Numbers

Natural Number:

A natural number, as the name implies, is a number that occurs often and clearly in nature. It is a whole number with no negative digits.

Some mathematicians agree that a natural number must contain 0 while others do not. As a result, a list of natural numbers can be described as follows

N= 1 , 2 , 3 , 4 , 5 etc.

Prerequisite:

  1. For Loop in python
  2. While Loop in python

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Examples:

Example 1:

Input :

number = 5

Output:

Sum of natural numbers till 5 = 15

Example 2:

Input :

number = 43

Output:

Sum of natural numbers till 43 = 946

Program to Find the Sum of Natural Numbers in Python

Below are the ways to print the sum of natural numbers in python:

Method #1:Using for loop

  • Take a variable say sum and initialize to 0
  • Iterate from 1 to N using for loop and range() function.
  • For each iteration add the iterater value to sum.
  • Print the sum.

Below is the implementation:

# given number
number = 5
# Take a variable say sum and initialize to 0.
sum = 0
# Iterate from 1 to number using for loop and range function
for i in range(1, number+1):
    # add the iterater value to sum.
    sum = sum + i
# print the sum
print("Sum of natural numbers till", number, "=", sum)

Output:

Sum of natural numbers till 5 = 15

Method #2:Using while loop

  • Take a variable say sum and initialize to 0
  • The while loop was used to iterate until number became zero.
  • In each loop iteration, we have added the number to sum and decreased the value of number by 1.
  • Print the sum.

Below is the implementation:

# given number
number = 5
# Take a variable say sum and initialize to 0.
sum = 0
# iterate till the number becomes 0 using while loop
while(number != 0):
    # add the number value to sum
    sum = sum+number
    # decrement the number
    number = number-1
# print the sum
print("Sum of natural numbers", "=", sum)

Output:

Sum of natural numbers = 15

Method #3:Using mathematical formula

Instead of iterating till number the best and efficient solution is to use mathematical formula given below.

Formula:

sum = ( n * (n +1) ) / 2

Below is the implementation:

# given number
number = 5
# Using mathematical formula
sum = (number * (number+1))//2
# print the sum
print("Sum of natural numbers till", number, "=", sum)

Output:

Sum of natural numbers till 5 = 15

Related Programs: