Which loop to use, for or do/while?

后端 未结 13 979
Happy的楠姐
Happy的楠姐 2021-01-19 23:02

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

相关标签:
13条回答
  • 2021-01-19 23:35

    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

    0 讨论(0)
  • 2021-01-19 23:39

    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.

    0 讨论(0)
  • 2021-01-19 23:42

    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.

    0 讨论(0)
  • 2021-01-19 23:45

    ((((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

    0 讨论(0)
  • 2021-01-19 23:46

    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.

    0 讨论(0)
  • 2021-01-19 23:50

    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)

    0 讨论(0)
提交回复
热议问题