2

In the week0 lecture David gives the following as an example of pseudocode:

let N=0,
for each person in room,
set N=N+1

He said this gets the value of 0 which proves that the algorithm is true.

But I am confused by this example, because in calculus we know that

if N=0,
then N=N+1,

and we know that N=0 and N=0+1=1 which says that this algorithm is false.

Why is the pseudocode algorithm true?

3 Answers 3

1

This type of loops has 3 main parts

  1. initialization (e.g., N = 0)
  2. the loop continuation condition — the code inside the body of the loop repeats as long as this condition evaluates to true (e.g., N is less than the number of persons in the room).
  3. the update — eventually causes the loop continuation condition to evaluate to false so that we don't become stuck into an infinite loop (that runs forever because the condition never becomes false). For example, N = N + 1 (i.e., increment N by 1).

The initialization step happens only once at the very first iteration (repetition) of the loop (it obviously doesn't make sense that every time the loop iterates, N is initialized with 0).

After the initialization, this is the order of the steps that a loop uses

  1. evaluate the loop continuation condition
  2. if it evaluates to true, execute the body of the loop
  3. perform the update
  4. go back to 1

That said, if the loop continuation condition evaluates to false (even initially), the body of the loop never gets executed again and the first thing after the loop is executed.

Hope that helps!

0

The logic is sequential in that it updates the value based on new information.

N starts at zero since that is how the variable is initialized.

The algorithm then updates the value of N to be equal to the value of N+1. It's not so much math syntax as it is computer science syntax.

N=N+1

translates to

Update the value of N to be equal to the previous value of N plus 1

The equals sign in C literally translates to "Set this equal to".

It is not a true mathematical expression as you state, in which case the answer reduces to be disproved, as below.

N = N+1  //begin
N - N = N+1 - N  //subtract n from both sides
0=1  //this is now proven incorrect
0

You probably tear out a piece which does not have sense by itself. If you take a bigger piece of text, you can understand that the line where N = N + 1 does not execute at all, if there are no people in the room. So, N does not increment and stays 0 by the end of the algorithm.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .