on
Italy
- Get link
- X
- Other Apps
# Python program to find the sum of natural numbers up to n where n is provided by user
# take input from the user
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate un till zero
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)
OutputEnter a number: 16 The sum is 136Here, we ask the user for a number and display the sum of natural numbers up to that number. We use
while
loop to iterate until the number becomes zero.n*(n+1)/2
. We could have used this formula directly. For example, if n = 16, the sum would be (16*17)/2 = 136.
Comments
Post a Comment