Sum of N natural numbers
Aim: Implement
a program to find the sum of natural numbers up to n where n is provided by
user.
Algorithm:
1.Start
2.Read
the limit ‘n’
3.
let i=0
4.for
i<=n repeat steps 5&6
5.sum=sum+i
6.i=i+1
7.print
sum
8.Stop
Program:
# take input from the
user
num =
int(input("Enter the limit: "))
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)
Output:
Enter the limit: 16
The sum is 136
0 Comments:
Post a Comment