How to reset counter in loop

前端 未结 4 1047

Here is my code

        int i = 0;
        while (i < 10)
        {
            i++;
            i = i % 10;
        }

The above code resets

相关标签:
4条回答
  • 2021-01-27 04:40

    By using this you can reset the value of i to 0 when reaches the limit 10.

    int i = 0;
    while (i < 10)
    {
       i++;
       if(i==10)
       {
          i=0;
       }
    }
    
    0 讨论(0)
  • 2021-01-27 04:44

    Your first loop iterates over the numbers 0..9. You can make your code iterate over 9..0 in the same way:

    int i = 10;
    while (i > -1)
    {
        i--;
        i = i % 10;
    }
    
    0 讨论(0)
  • 2021-01-27 04:45
        int i = 10;
        while (true)
        {
            i = (i + 10) % 11;
        }
    

    This would give you:

    10 -> 9
    9 -> 8
    8 -> 7
    7 -> 6
    6 -> 5
    4 -> 3
    3 -> 2
    2 -> 1
    1 -> 0
    0 -> 10
    
    0 讨论(0)
  • 2021-01-27 05:01

    Both your loops are while(true) so they play no role in the question.

    That leaves: "can I make a count-down roll over without an if?"

    The answer is yes, if you realy want to:

     i--;
     i = (i + 10) % 10;
    
    0 讨论(0)
提交回复
热议问题