0

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
IT ken
  • 5
  • 1
  • 1
  • 10
  • 2
    There's no loop here. This will read at most 2 numbers then stop. –  Oct 15 '14 at 02:15
  • How can i correct this. – IT ken Oct 15 '14 at 02:30
  • Do you have examples of the preferred format of pseudo-code for your course? If so, look for loops and see how they are presented. Meanwhile, pretend you are a really stupid computer, try to follow your code with pencil and paper, and see what happens. – Patricia Shanahan Oct 15 '14 at 02:38

4 Answers4

0

Bugs

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

Possible Bugs

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

Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69
0

I think you are using do while loop and i made some changes to your algorithm. i think it solves your 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=sum+number
8. while (n==0)
9. print sum
10.Stop
Karunakar
  • 2,209
  • 4
  • 15
  • 20
  • thank you again for the help, i really do appreciate it.Its been hard for me to make the transition from business an economic principles into IT. – IT ken Oct 15 '14 at 04:49
0

number+sum should be sum+=numberbecause you need to add the value of the number to the sum, the number+sum isn't assigned anywhere.

RE60K
  • 621
  • 1
  • 7
  • 26
0

You need to add below two inside the loop

6. n=number%2
7. If (n==0) then sum+=number

or else it will be an infinite loop or until some one enters an odd number.

Aniruddh
  • 188
  • 5
  • 24