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 se
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
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.
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.
((((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
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.
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)