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 wich would use as max the length of the word passed to it and the method used to cycle trough the for was the first, can anyone clarify me开发者_Go百科 why the person who writed that piece of code prefeered using that method ?
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.
Both the loops will iterate max
times. But the ranges would be different:
- First loop's range would be
max - 1
to0
(both inclusive) - Second second loop's range would be
max
to1
.
Therefore, if you are using i
as an array index, or doing some work which is a function of i
, dependent of i
, then it will create problems for the terminal values (for example 0
is considered in the first one, where as not by the second one). But if you simply want to iterate the loop max
nos of times , and do some work which is independent of the value of i
, then there is no difference.
精彩评论