158k views
24 votes
Write a program that asks the user for a positive nonzero integer value. The program should use a loop to get the sum of all the integers from 1 up to the number entered. For, example if the user enters 50 , the loop will find the sum of 1,2,3,4,...,50. while loop

2 Answers

8 votes

Final answer:

To calculate the sum of integers using a while loop, prompt the user for input, initialize a sum variable to 0, use the while loop to iterate and add each number to the sum, then display the sum.

Step-by-step explanation:

To write a program that calculates the sum of all integers from 1 up to a user-specified number using a while loop, you can follow these steps:

  1. Prompt the user to enter a positive nonzero integer.
  2. Initialize a variable to store the sum as 0.
  3. Use a while loop to iterate from 1 up to the entered number.
  4. Inside the loop, add the current number to the sum variable.
  5. After the loop, display the sum to the user.

Here's an example implementation in Python:

number = int(input('Enter a positive nonzero integer: '))
sum = 0
while number > 0:
sum += number
number -= 1
print('The sum is:', sum)
User Adeel ASIF
by
3.0k points
13 votes

num = 0

while num <= 0:

num = int(input("Enter a number: "))

i = 1

total = 0

while i <= num:

total += i

i += 1

print(total)

I wrote my code in python 3.8. Best of luck.

User BillyTom
by
3.6k points