开发者

For cycle [C/java like syntax]

开发者 https://www.devze.com 2023-04-11 10:40 出处:网络
So here I am with this simple question Consider these two for cycles and please explain to me if there\'s any difference

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 to 0 (both inclusive)
  • Second second loop's range would be max to 1.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消