Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the preferred condition in loop?

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

like image 793
yesraaj Avatar asked Jan 25 '09 10:01

yesraaj


People also ask

Which condition we can use in for loop?

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.

What is a condition in loop statement?

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.

What are the types of conditional loops?

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.

Which is the best looping statement and why?

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.


2 Answers

The second. For two reasons

  1. 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.

  2. 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.

like image 84
Cruachan Avatar answered Sep 22 '22 10:09

Cruachan


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.

like image 41
Paul Dixon Avatar answered Sep 21 '22 10:09

Paul Dixon