tags:

views:

401

answers:

13

Using C# (or VB.NET) which loop (for loop or do/while loop) should be used when a counter is required?

Does it make a difference if the loop should only iterate a set number of times or through a set range?

Scenario A - The for loop

for (int iLoop = 0; iLoop < int.MaxValue; iLoop++)
{
  //Maybe do work here

  //Test criteria
  if (Criteria)
  {
    //Exit the loop
    break;
  }

  //Maybe do work here
}

Advantages

  • Counter is declared as part of loop
  • Easy to implement counter range

Disadvantages

  • Have to use an if to leave the loop

Scenario B - The do/while loop

int iLoop = 0;
do
{
  //Increment the counter
  iLoop++;

  //Do work here
} while (Criteria);

or

int iLoop = 0;
while (Criteria)
{
  //Increment the counter
  iLoop++; 

  //Do work here 
}

Advantages

  • Leaving the loop is part of the loop structure
  • Choice to evaluate before or after loop block

Disadvantages

  • Have to manage the counter manually
A: 

I ususually use for, cause it's simple. I use while when counter is needed after or before loop or if using for is impossible.

x2
+8  A: 

How about the best of both worlds:

for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)

Edit: Now that I think about it, I suppose comparing against int.MaxValue wasn't part of the criteria, but something to emulate an endless for loop, in that case you could just use:

for (int iLoop = 0; !Criterea; iLoop++)
Firas Assaad
Except he said there might be some work to do before checking Criteria
Daphna Shezaf
@Daphna Shezaf: You're right, but you'd still need to have an if condition inside a while loop if you want to do some work before and after checking it
Firas Assaad
@Firas - But no if if you only want to check a criteria after the loop body (do loop). I do like this construct tho.
Stevo3000
@Stevo3000: Yeah, it depends on what you want to do. I was referring to your for loop example where you had "may do work here" comments before and after the check for criteria.
Firas Assaad
A: 

At least for me i use for() when i need to traverse an array and when no breaking is needed. And do() and while() when i need to process something for an unknown time.

Ólafur Waage
+1  A: 

You can always add the exit criteria to for loop:

for (int iLoop = 0; iLoop < int.MaxValue && Criteria; iLoop++)
{
  //Maybe do work here
}

I would really go for whatever looks most readable in your particular case.

Grzenio
+3  A: 
for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++) {
    //Do work here...
}
Matt Howells
+1  A: 

There's no reason not to use a for loop in this case. Even if you have other criteria, it's perfectly valid to write:

for (int iLoop = 0; iLoop < int.MaxValue && Criteria; iLoop++) { ... }
VoteyDisciple
+1  A: 

Personally I would go with the for loop.

It is better to read, more commonly used and very optimized.

for (int iLoop = 0; iLoop < int.MaxValue && !Criteria; iLoop++)
{
// Do Work
}

Edit: int.MaxValue && !Criteria <- a definietely better approach than my initial one ;)

Shaharyar
++iLoop or iLoop++ makes no difference in C#, this will compile to the same IL. If you don't believe me, try it.
Matt Howells
-1 for the wrong information about ++. It would never create a temporary variable in this case (and pretty much never in general either).
Blindy
I disagree; pre-increment operators are relatively rare, and in C# offer no tangible performance improvement. You are adding uncertainty / confusion for no reason.
Marc Gravell
Edited the anwer, thanks for letting me know - didn't know that it didn't matter in C# - at work I was told to use the ++ before the iterator...
Shaharyar
integers aren't iterator objects.
Blindy
what exactly is meant by the iterator then? (is it the object you use in a forearch loop?
Shaharyar
+1  A: 

for loops consist of the following:

for ( initialization; condition; action )

you don’t need an extra if to check your criteria, what do you think is i < value? it’s nothing more than a criteria.

i use loops when they fit the problem, there’s no definite answer

knittl
+9  A: 

Just for completeness, you could also use option D:

for (int iLoop = 0; Criteria; iLoop++)
{
   // work here
}

(where Criteria is "to keep running")

the condition in a for loop doesn't have to involve iLoop. Unusual, though, but quite cute - only evaluates before work, though.

Marc Gravell
So a for loop can replicate the while loop without an if, but a for loop needs an if to replicate a do loop!
Stevo3000
and maybe even do not write iLoop++ because Criteria might not depend upon iLoop
Luis Filipe
Well, it is suggested that the counter is needed, and it is nice to keep the increment away from the "meat" of the code.
Marc Gravell
@Luis Filipe - @Marc is correct, the counter is part of the question.
Stevo3000
+3  A: 

Instead of a dummy criteria in the for loop, you can use the actual criteria that you want to use for the loop:

Scenario A2 - the for loop with custom criteria:

for (int iLoop = 0; Criteria; iLoop++) {

  // do work here

}

This is equivalent to:

{
   int iLoop = 0;
   while (Criteria) {

      // do work here

      iLoop++;
   }
}

If you have a loop counter, you should generally use a for loop to make that clearer.

Guffa
+1  A: 

Write some test cases and see which works best for you. Have a look a this link: .Net/C# Loop Performance Test (FOR, FOREACH, LINQ, & Lambda)

Mr. Smith
+1  A: 

I'd tend to use for if I'm actually using the counter in the loop, say as an index into an array, and as part of the criteria, i.e. "stop at the end of the array" rather than "just don't overflow".

If I'm looping over something with unknown length, such as lines in a file, or just maintaining the counter to use the total after the loop, then I'll use do or while.

However, it really comes down to what's more readable for a particular situation. I expect that you'd struggle to tell from the compiled IL which version was used.

stevemegson
+1  A: 

((((difference b/w while and do while--> let me tell you with one example : if a person going into a hall to fix a bomb inside the hall, he must be checked when getting in.. in another case if a person going into a hall to steal something from there he must have been checked when coming out of the hall.. so based on the process only we have to use our looping condition....))))

The for loop can execute a block of code for a fixed or given number of times.if your counter variable depends on that block of code(means inside the looping condition), you can use the for loop