Site icon codemaniacstudio

Write a Python program to find sum of all natural numbers between 1 to n.

Write a Python program to find sum of all natural numbers between 1 to n.

SOLUTION....

# Program to find sum of all natural numbers between 1 to n using while loop

# Input from user
n = int(input("Enter a number: "))

i = 1       # starting number
total = 0   # variable to store sum

while i <= n:
    total += i   # add i to total
    i += 1       # increment i by 1

print("Sum of natural numbers from 1 to", n, "is:", total)

OUTPUT

Exit mobile version