Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which loop to use, for or do/while?

Tags:

c#

loops

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
like image 973
stevehipwell Avatar asked Nov 28 '22 05:11

stevehipwell


2 Answers

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.

like image 123
Marc Gravell Avatar answered Dec 19 '22 09:12

Marc Gravell


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++)
like image 45
Firas Assaad Avatar answered Dec 19 '22 09:12

Firas Assaad