Algorithm
- Input: Take an input
n
from the user, representing the last natural number in the series. - Initialize: Set a variable
sum
to 0 to store the cumulative sum. - Loop: Use a loop to iterate from 1 to
n
.- In each iteration, add the current number to the
sum
. - Output: Display the final value of
sum
as the sum of natural numbers.
- In each iteration, add the current number to the
Code Examples
#1 Example- Python Program to Find the Sum of Natural Numbers
Code -
Python Programming
#Taking user input
num = int(input('Enter a number:'))
if num < 0:
num = input('Please enter a positive number:')
else:
sum = 0
#Loop to iterate till zero
while(num > 0):
sum += num
num -= 1
print("The sum of the natural numbers is:", sum)
Copy The Code &
Try With Live Editor
Output
Enter a number:15
The sum of the natural numbers is: 120
The sum of the natural numbers is: 120
Demonstration
Python Programing to Find the Sum of Natural Numbers-DevsEnv