In this example you will learn how to find the sum of natural number using three different ways.
- Using a For Loop
- Using a natural sum formulae
- Using Recursion
Using For loop
# get input from the user
n = int(input("Enter a number: "))
# calculate the sum using the formula
sum = n * (n+1) // 2
# print the sum
print("The sum of natural numbers up to", n, "is", sum)
Output
Enter a number: 12
The sum of natural numbers up to 12 is 78
Here in this program first get the input from the user using the input() function and convert it to an integer using int() built-in function, after that we then initialize a variable sum to 0 and use a Python for loop to iterate from 1 to n. In each iteration, we add the value of i to the sum. Finally, we print out the sum of natural numbers up to n.
Using the formula
We use mathematical arithmetic series formula sum = n * (n + 1 ) / 2
# get input from the user
n = int(input("Enter a number: "))
# calculate the sum using the formula
sum = n * (n+1) / 2
# print the sum
print("The sum of natural numbers up to", n, "is", sum)
Output
Enter a number: 145
The sum of natural numbers up to 145 is 10585.0
Using Recursion
# define a function to calculate the sum of natural numbers recursively
def sum_natural(n):
if n == 0:
return 0
else:
return n + sum_natural(n-1)
# get input from the user
n = int(input("Enter a number: "))
# call the function to calculate the sum
sum = sum_natural(n)
# print the sum
print("The sum of natural numbers up to", n, "is", sum)
Output
Enter a number: 56
The sum of natural numbers up to 56 is 1596
The recursion example calculates the sum of natural numbers by repeatedly adding the current number to the result and calling the function again with the next lower number until the base case is reached.