How to perform an action every 5 results?

前端 未结 6 1485
春和景丽
春和景丽 2020-11-30 09:28

How can I perform an action within a for loop every 5 results?

Basically I\'m just trying to emulate a table with 5 columns.

6条回答
  •  再見小時候
    2020-11-30 09:34

    It's possible to use a condition with a modulus, as pointed out. You can also do it with nesting loops.

    int n = 500;
    int i = 0;
    
    int limit = n - 5
    (while i < limit)
    {
       int innerLimit = i + 5
       while(i < innerLimit)
       {
           //loop body
           ++i;
       }
       //Fire an action
    }
    

    This works well if n is guaranteed to be a multiple of 5, or if you don't care about firing an extra event at the end. Otherwise you have to add this to the end, and it makes it less pretty.

    //If n is not guaranteed to be a multiple of 5.
    while(i < n)
    {
      //loop body
      ++i;
    }
    

    and change int limit = n - 5 to int limit = n - 5 - (n % 5)

提交回复
热议问题