To understand this example, you should have the knowledge of following Python programming topics:
In the program below, we've used an if else statement in combination with a while loop to calculate the sum of natural numbers upto num.
# Python program to find the sum of natural numbers up to n where n is provided by user # change this value for a different result num = 16 # uncomment to 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)
Output
The sum is 136
Note: To test the program, change the value of num.
Here, we store the number in num and display the sum of natural numbers up to that number. We use while
loop to iterate until the number becomes zero.
We could have solved the above problem without using any loops using a formula directly.
Your turn: Modify the above program to find the sum of natural numbers using the formula below.
n*(n+1)/2
For example, if n = 16, the sum would be (16*17)/2 = 136.
It takes a lot of effort and cost to maintain Programiz. We would be grateful if you support us by either:
Disabling AdBlock on Programiz. We do not use intrusive ads.
or
Donate on Paypal