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?
12 Answers
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
tokeyword in aforloop syntax, where the value that followstois not to be included in the iterations. On the other hand, BASIC like languages (such as vba) 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
tokeyword is used, the final iteration is using that value. - If the intention of this loop is to visit each value in an array of
nelements (a very common case), then there is no ambiguity:for i = 1 to ntells us that the array's first element has position 1, and hence its last position is positionn. 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 seefor i = 0 to nin pseudo code, some alarms should go off. That definitely would come across ambiguous.
It is highly contextual and depends on the person who wrote it. (It also kind of depends on the programming language that the pseudocode is aimed to be converted to.)
If it were in an interview setting, it might be a good idea to ask if this is "inclusive of n or not". Because it could be either case.
(I know this answer might not be that helpful. Sorry about that, but it doesn't seem that this has a definitive answer.)
8ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobXBxZG6FcoWOqaqerZSksLCwxGauoqyYYrOwvoylpqio