Python Program - Calculate sum of Natural numbers
In Mathematics, the natural numbers are all positive numbers which is used for counting like 1, 2, 3, 4, and so on. The smallest natural number is 1.
Objective: Write a Python program which returns sum of natural numbers starting from 1 to given natural number n, (1 + 2 + 3 + ... + n).
Method 1: Using while loop
The example below shows how to use while loop to calculate sum of first n natural numbers.
n = 10 i = 1 sum = 0 #calculating sum from 1 to n while(i <= n): sum += i i += 1 print("Sum is:", sum)
The above code will give the following output:
Sum is: 55
Method 2: Using for loop
The same can be achieved using for loop. Consider the example below:
n = 10 sum = 0 #calculating sum from 1 to n for i in range(1, n+1): sum += i print("Sum is:", sum)
The above code will give the following output:
Sum is: 55
Method 3: Using Recursion
Similarly, recursion can be used to calculate the sum.
#recursive function def Sum(n): if(n == 1): return 1 else: return (n + Sum(n-1)) print("Sum of first 10 natural numbers:", Sum(10)) print("Sum of first 20 natural numbers:", Sum(20))
The above code will give the following output:
Sum of first 10 natural numbers: 55 Sum of first 20 natural numbers: 210
Method 4: Using Mathematical Formula
The sum of first n natural numbers can be mathematically expressed as:
n = 10 #calculating sum from 1 to n sum = n*(n+1)/2 print("Sum is:", sum)
The above code will give the following output:
Sum is: 55.0
Recommended Pages
- Python Program - To Check Prime Number
- Python Program - Bubble Sort
- Python Program - Selection Sort
- Python Program - Maximum Subarray Sum
- Python Program - Reverse digits of a given Integer
- Python - Swap two numbers
- Python Program - Fibonacci Sequence
- Python Program - Insertion Sort
- Python Program - Find Factorial of a Number
- Python Program - Find HCF of Two Numbers
- Python Program - Merge Sort
- Python Program - Shell Sort
- Stack in Python
- Queue in Python
- Python Program - Find LCM of Two Numbers
- Python Program - To Check Whether a Number is Palindrome or Not
- Python Program - To Check Whether a String is Palindrome or Not
- Python Program - Heap Sort
- Python Program - Quick Sort
- Python - Swap Two Numbers without using Temporary Variable