175k views
15 votes
4.8.4 Better Sum

Write a program that asks the user for two numbers. Using a for loop, add all of the numbers from the first to the second.


For example if the first number is 6 and the second number is 8 the result is 21 (6 + 7 + 8).


Print out the results when you are finished.

write in python

User Mateos
by
4.2k points

2 Answers

3 votes

Final answer:

To solve this problem, you can use a for loop to iterate through the range of numbers from the first number to the second number and add them all up. Here's an example of how you can write the code in Python.

Step-by-step explanation:

To solve this problem, you can use a for loop to iterate through the range of numbers from the first number to the second number. You can then use an accumulator variable to keep track of the sum of all the numbers. Here's an example of how you can write the code in Python:

first_number = int(input('Enter the first number: '))
second_number = int(input('Enter the second number: '))

sum = 0
for num in range(first_number, second_number + 1):
sum += num

print('The sum is:', sum)

In this code, the variable 'sum' is initially set to 0. The for loop will iterate through each number in the range from the first number to the second number, and add it to the 'sum'. Finally, the total sum is printed out.

User Lukor
by
3.6k points
5 votes

Final answer:

To solve this problem, you can use a for loop to iterate through all the numbers between the first and second numbers and add them together. Finally, print out the sum when the loop is finished.

Step-by-step explanation:

To solve this problem, you can use a for loop to iterate through all the numbers between the first and second numbers. In each iteration, you can add the current number to a running sum. Finally, you can print out the sum when the loop is finished.

Here's the Python code that accomplishes this:

first_num = int(input('Enter the first number: '))
second_num = int(input('Enter the second number: '))
sum = 0
for num in range(first_num, second_num + 1):
sum += num
print('The sum is:', sum)

For example, if the user enters 6 as the first number and 8 as the second number, this program will output:

The sum is: 21

User Lyubomyr Dutko
by
3.1k points