Search code examples
pseudocode

Pseudocode - What is wrong about this


I AM TRYING TO FIND THE ERROR

The code is supposed to find out if a positive integer entered by a user is exactly divisible by the number 3.

n = userinput
WHILE n ≥ 0
  n = n - 3
ENDWHILE

Solution

  • You're using greater than OR EQUAL TO so you won't break out of the loop on n = 0, only n = -3 which then triggers your ELSE statement. The EQUAL TO aspect takes you a step too far.

    Answering the comment: Use > instead of >=. Basically the code as written will never allow n to equal 0 at the time the condition is evaluated. Trace each step of the loop using a number like 3.

    N = 3
    //first pass
    WHILE (3 >= 0) // true
    n = 3-3 //n now 0
    
    //second pass
    WHILE (0 >= 0) //True, 0 is equal to 0
    n = 0-3 //n now -3
    
    //third pass
    WHILE(-3 >= 0) //False break out of loop
    
    IF(-3 == 0) // false so we jump to the else
    
    ELSE: 3 is not divisible by 3.
    

    One quick way to easily spot check your loops that aren't performing as expected is to just manually run through them with an easy input.