Search code examples
javac++calgorithm

For cycle [C/java like syntax]


So here I am with this simple question

Consider these two for cycles and please explain to me if there's any difference between the two ways of writing

method 1:

  for(i=(max-1) ; i>=0 ; i--){ do-some-stuff }

method 2:

  for(i=max ; i>0 ; i--)     { do-some-stuff }

the reason I'm asking this is because today at school while we were seeing some Java functions, there was this palindrome method which would use as max the length of the word passed to it and the method used to cycle through the for was the first, can anyone clarify me why the person who wrote that piece of code preferred using that method?


Solution

  • Yes, there's a big difference - in the version, the range is [0, max-1]. In the second version, it's [1, max]. If you're trying to access a 0-based array with max elements, for example, the second version will blow up and the first won't.

    If the order in which the loop ran didn't matter, I'd personally use the more idiomatic ascending sequence:

    for (int i = 0; i < max; i++)
    

    ... but when descending, the first form gives the same range of values as this, just in the opposite order.