In the program below, we've used an if...else
statement in combination with a while loop to calculate the sum of natural numbers up to num.
Source Code
# Sum of natural numbers up to num
num = 16
if num < 0:
print["Enter a positive number"]
else:
sum = 0
# use while loop to iterate until zero
while[num > 0]:
sum += num
num -= 1
print["The sum is", sum]
Output
The sum is 136
Note: To test the program for a different number, change the value of num.
Initially, the sum is initialized to 0. And, the number is stored in variable num.
Then, we used the while
loop to iterate until
num becomes zero. In each iteration of the loop, we have added the num to sum and the value of num is decreased by 1.
We could have solved the above problem without using a loop by using the following formula.
n*[n+1]/2
For example, if n = 16, the sum would be [16*17]/2 = 136.
Your turn: Modify the above program to find the sum of natural numbers using the formula below.
- Home
- PHP
- MySQL
- MongoDB
- HTML
- Javascript
- Node.js
- Express.js
- Python
- Jquery
- R
- Kotlin
- DS
- Blogs
- Theory of Computation
General Knowledge
Learn Popular Language
A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities... In this article, we have mentioned the analyzed results of the best programming language for 2021... Python has a set of useful Libraries and Packages that minimize the use of code... In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more... In this
article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...Blogs
Stateful vs Stateless
Best programming language to learn in 2021
How is Python best for mobile app development?
Learn all about Emoji
Data Science Recruitment of Freshers
Follow us
- eTutorialsPoint©Copyright 2016-2022. All Rights Reserved.
The question was tp :write a program to find the sum of n natural numbers using while loop in python.
n = int[input["Enter a number: "]]
i = 1
while i 0]:
totalSum += number
number -= 1
print ["The sum is" , totalSum]
answered Jul 28 at 21:45
num = int[input['Enter the number : ']]
sum = 0
while 0 0]:.