int n = 5;
for(int i = 0;i!=n;i++)//condition !=
{
//executing 5times
}
int n = 5;
for(int i = 0;i<n;i++)//condition <
{
//executing 5times
}
Which one is preferred?
This was example from "Accelerated C++ : practical programming by example / Andrew Koenig, Barbara E. Moo." Just wanted to know why the Author prefers the first one
In general, you should use a for loop when you know how many times the loop should run. If you want the loop to break based on a condition other than the number of times it runs, you should use a while loop.
Loop statements test a condition to determine how many times to repeat a set of statements. Something in the loop must change the initial condition tested.
There are two types of conditional loops, DO WHILE and DO UNTIL. One or more expressions control both types of loops. However, DO WHILE loops test the expression before the loop executes the first time and repeat only when the expression is true.
The for loop is probably the most common and well known type of loop in any programming language. For can be used to iterate through the elements of an array: For can also be used to perform a fixed number of iterations: By default the increment is one.
The second. For two reasons
The less than (or sometimes <=) is the usual way that most coder write these, and it's better to stick to convention if possible - the != will probably make most coders look twice to check if there's something odd in the loop whereas the < will be instantly understood.
The != depends on an exact condition. If the interior of the loop is modified during maintenance and i accidentally incremented inside the loop then you would end up with an infinite loop. Generally it's always better to make your termination condition as wide as possible - it's simply more robust.
2 is of course the reason why 1.
I would say <
as it captures a wider set of conditions. Suppose that n wasn't constant but returned from a function which on rare occasions returned -1. In that event, you'd have a much longer loop (until the int wraps around to a -ve value!) with the != version of the loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With