65.9k views
4 votes
Write a program with a loop that asks the user to enter a series of positive numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum. Note: Don’t include the negative number in the sum. Pay attention on the fact that, as a programmer you have no idea how many positive numbers user is going to enter. Pick your loop wisely. Design your code your way!!

1 Answer

6 votes

Those kind of loops are well implemented by a do-while loop: you should write your code following this logic (you didn't specify any particular language, so I'll just write down the logic in pseudo code):

sum=0;

do {

num = prompt(number);

if(number>0) {

sum = sum+number;

}

while (number>0);

print(sum);

So, what we're doing is:

  1. Initialize the final sum as zero
  2. Ask the user for a number
  3. If the number is not negative, add it to the (partial) sum
  4. Loop steps 2-3 untile we get a negative value
  5. Print the final value of the sum
User Anand Mishra
by
5.6k points