Sum of n Natural numbers - Learn Engineering

All the news and updates relevant to Engineering. You can also Write a post here

Breaking

Friday, June 19, 2020

Sum of n Natural numbers

python-mini

Question

To Count the sum of n Natural numbers.

Sample TestCaseExpected Output

Enter the n : 3                                                                    Sum of first 3 natural numbers is 6

Answer


num=int(input("Enter  the n : "))
hold=num
sum=0
if num<=0:
    print("Enter a Positive number")
else:
    while num>0:
        sum+=num
        num=num-1
print("Sum of first ",hold,"natural numbers is ",sum)

No comments:

Post a Comment