Alex Rivera | Logout

How to perform an action every 5 results?

Asked 2009-09-30T21:08:05.290
15

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.

Edit
Report

1 Answer

0

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)

answered 2009-09-30T21:30:26.307

Your Answer