Search code examples
algorithmpseudocode

pseudocode with for loop


I have some confusion in:

for i = 1 to n

does this pseudocode code means for(i=1; i<n; i++) or for(i=1; i<=n; i++) ?

And if one from them, then what will be the pseudocode for another one?


Solution

  • It should be understood to include an iteration where i takes the value of n.

    However, there are no strict rules for pseudo code, and so in case there is doubt about an actual piece of pseudo code, then this means that code didn't achieve what it was supposed to do: unambiguously describe an algorithm without any programming language in mind.

    Here are some of the arguments why it should be understood to include n:

    • When in plain English we tell someone to count from 1 "to 100", we mean that they should include 100 at the end. This is probably the strongest argument.
    • I know of no programming language that uses the to keyword in a for loop syntax, where the value that follows to is not to be included in the iterations. On the other hand, BASIC like languages (such as ) have that syntax, and the "to" value will be used for the final iteration.
    • On Wikipedia some examples of pseudo code loops are given, and where the to keyword is used, the final iteration is using that value.
    • If the intention of this loop is to visit each value in an array of n elements (a very common case), then there is no ambiguity: for i = 1 to n tells us that the array's first element has position 1, and hence its last position is position n. It is not uncommon to use such 1-based indexing of arrays in pseudo code, as this is more intutive to non-programmers. If however in such array context you see for i = 0 to n in pseudo code, some alarms should go off. That definitely would come across ambiguous.