I am faced with a question that goes like this:
Write pseudocode that allows a user to repeatedly enter positive integers until an odd number is entered. It would then print the sum of all numbers entered (excluding the odd number).
Example: given that the user enters
2 24 16 8 7 the program would print 50.
I would like to get some feedback on my algorithm for this problem.
1. Start 2. Declare int number,n,sum=0 3. Do 4. Input number 5. Read number 6. n=number%2 7. If (n==0) then sum+=number 8. while (n==0) 9. If(n==1) then display number and print sum 10. Endif 11. Endwhile 11. Stop
You need to move a copy of line 5 (n=number%2) inside of the loop - right now you've got an infinite loop if
n == 0 because
n is not modified inside of the loop
Some languages will return a negative value on the modulo operation if the dividend or divisor is negative, so you may want to take the absolute value of the remainder (n=abs(number%2))
Formatting / Syntax
This is a case where you should use a do while loop - this will let you eliminate lines 3 through 5
Indent the stuff inside the loop