2

We can use for loop and while loop for same purpose. in what means they effect our code if I use for instead of while? same question arises between if-else and switch-case? how to decide what to use? for example which one you would prefer?

This code:

int main()
{
   int n = 10;

   for(int i=0;i<n;i++)
    {
        do_something();
    }
    return 0;
}

Or this code:

int main()
{
    int n=10,i=0;

    while(i<n)
    {
          do_something();
          i++;
    }
    return 0;
}

if using for or while loop does not effect the code by any means then may I know What was the need to make 2 solution for same problem?

SiegeX
  • 135,741
  • 24
  • 144
  • 154
Atul
  • 1,157
  • 2
  • 16
  • 28

8 Answers8

15

Use whichever one makes the intention of your code clearest.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
10

If you know the number of iterations the loop should run beforehand, I would recommend the for construct. While loops are good for when the loop's terminating condition happens at some yet-to-be determined time.

SiegeX
  • 135,741
  • 24
  • 144
  • 154
5

I try to prefer the for loop. Why? Because when I see a for loop, I can expect all of the loop bookeeping is kept in a single statement. I can insert break or continue statements without worrying about breaking how the loop operates. And most importantly, the body of the loop focuses on what you actually want the loop to be doing, rather than maintaining the loop itself. If I see a while, then I have to look at and understand the entire loop body before I can understand what iteration pattern the loop uses.

The only place I end up using while is for those few cases where the control of the loop is provided by some outside routine (i.e. FindFirstFileW)

It's all a matter of personal opinion though. Lots of people don't like what I end up doing with for loops because the loop statement often ends up spanning multiple lines.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
  • 1
    can you give some example, where for loop head spans multiple lines? – Herdsman May 12 '20 at 17:59
  • +1 for putting the loop bookkeeping all in one place. But I'd say never mix styles—i.e., as soon as *some* of the loop bookkeeping has to happen *inside* the loop body, use a `while` loop; use a `for` loop where everything related to the loop flow is handled in the header. This way, when you see a `for`, as you mention, you are free to use `break` and `continue` without worrying. – Anakhand Jul 03 '20 at 13:22
2

In general, a for loop might be preferable for simple loops, since the logic of the loop is contained in a single line:

for (int i = 0; i < 10; ++i) {...}

However, sometimes we need more complex logic or flow control. A while loop allows us to implement more complicated loops. For example, suppose we only want to increment the counter variable under certain conditions:

int i = 0;
while (i < 10)
{
  if (some_condition) ++i;
  else if (some_other_condition) { ... }
  else break;
}
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
  • I don't see this argument. Just replace the first two lines with `for(int i = 0;i < 10;)` and you have the same loop. (And have the bonus of restricting the scope if `i`). – Billy ONeal Jan 09 '11 at 19:31
  • @Billy ONeal, true - but following that to the extreme we can conclude that `while` is totally superfluous, since any `while (condition)` can be replaced with `for (;condition;)`. It's subjective, but I think `while` may be a clearer choice if the counter variable is updated conditionally, since someone reading the code usually expects a typical `for` loop to include a (non-conditional) counter-variable update. – Charles Salvia Jan 09 '11 at 19:59
2

There are some very subtle differences..

  • scope of loop variable(s), for example, with the for loop i has local scope, with a while this has to be defined before (which means it is available after, of course you can do that with for as well..)
  • continue, with a for loop, variable will be increment/decremented, with a while, you'd have to insert the operation before continue

Frankly, if you need to increment/decrement, a for loop makes sense, if you don't know the bounds, and there is no real increment/decrement, a while loop makes more sense, e.g.

while(some_stream >> input)
{
  // do stuff...
}
Nim
  • 33,299
  • 2
  • 62
  • 101
1

You cannot write while(int i=0, i < n); that is, you've to define i before the while loop; means i exists inside as well as outside the loop.

However, in case of for loop, you can define i right in the for loop itself; and so i doesn't exist outside the loop. That is one difference. Just because of this difference, I like for more than while. And use while rarely, when for makes thing more cumbersome!

Nawaz
  • 353,942
  • 115
  • 666
  • 851
1

Just use the one that makes the code readable and logical.

In some cases the compiler (gcc at least) will be able to optimize a very slightly better than a for loop doing the same thing. If I remember correctly that optimization is only about few clock cycles so it probably never will have any noticeable affect on the performance.

0xHenry
  • 512
  • 3
  • 12
0

By no means they affect your program the way it works ! Its the matter of ease to understand better.

switch(i)     // Once finding your case, you can easily know where the switch ends
              // and thus the next statement of execution
{
    case 1: break ;
    case 2: break ;
    // .....
    case 10: break ;
    default:break ;
}

if( i==1 )   // Here you have the pain of finding where the last else if ends !
{}
else if( i==2)
{}
// ...
else if( i==10)
{}

However, it is a matter of taste. I prefer switch.

Mahesh
  • 34,573
  • 20
  • 89
  • 115