Write a Python Program to find the Sum of N Natural Numbers using While Loop, For Loop, Functions, and recursion with an example. To achieve the same, we need a loop to iterate the numbers from 1 to N and then the arithmetic operator + to add those items to the total.
Python Program to find Sum of N Natural Numbers using For Loop
This program allows users to enter any integer value. Next, it calculates the sum of natural numbers from 1 to a user-specified value using For Loop. If you want a more dynamic approach, allow the user to enter the starting value and replace 1 in the for loop with the user-entered start value.
The for loop iteration starts at one and traverses up to the user-given number. Within the loop, each value will be added to the total variable to find the sum of integers.
number = int(input("Please Enter any Number: ")) total = 0 for value in range(1, number + 1): total = total + value print("The Sum from 1 to {0} = {1}".format(number, total))
Python Program to find Sum of N Natural Numbers using While Loop
In this program, we just replaced the For Loop with the While Loop. Don’t forget to initialize the value to 1 and increment by one (value = value + 1).
num = int(input("Please Enter any Num: ")) total = 0 value = 1 while (value <= num): total = total + value value = value + 1 print("The Sum from 1 to {0} = {1}".format(num, total))
Using Functions
In this program, we created a new function to find the sum of natural numbers. Inside this function, we used the If Else statement.
def sum_of_n_natural_numbers(num): if(num == 0): return num else: return (num * (num + 1) / 2) number = int(input("Please Enter any Number: ")) total_value = sum_of_n_natural_numbers(number) print("Sum from 1 to {0} = {1}".format(number, total_value))
Please Enter any Number: 100
Sum from 1 to 100 = 5050.0
The sum of N Natural Numbers using Recursion
This program is the same as the above example, but we are using Recursion now. The return (num + sum_of_n_natural_numbers(num – 1)) line calls the function recursively with the updated value.
def sum_of_n_natural_numbers(num): if(num == 0): return num else: return (num + sum_of_n_natural_numbers(num - 1)) number = int(input("Please Enter any Number: ")) total_value = sum_of_n_natural_numbers(number) print("Sum of Natural Numbers from 1 to {0} = {1}".format(number, total_value))