views:

360

answers:

5

can someone tell me the logic (in any language ) including pseudo code. on how to create a for loop an have it fire an action every 5 results it spits out.

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

Thanks!

+12  A: 

you could use the modulus operator

for(int i = 0; i < 500; i++)
{
    if(i % 5 == 0)
    {
        //do your stuff here
    }
}
John Boker
If the circumstances permit you can also just use `for ($i = 0; $i < 500; $i += 5) { ... }`.
Joey
@Johannes I think he wants to do processing for every whole number from 0 to n, but fire an action for every 5th element. I could be mistaken, though.
patros
Note that `(i%5==0)` will run on the first, sixth, eleventh, … passes. Use `(i%5==4)` to trigger on the fifth, tenth, fifteenth, … passes instead.
Ben Blank
For the sake of clarity this is one of those times the loop should start at 1 as the index because using 0 makes it not as clear.
Woot4Moo
A: 

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)

patros
A: 

For an HTML table, try this.

<?php
$start = 0;
$end = 22;
$split = 5;
?>
<table>
    <tr>
  <?php for($i = $start; $i < $end; $i++) { ?>
    <td style="border:1px solid red;" >
         <?= $i; ?>
    </td>
    <?php if(($i) % ($split) == $split-1){ ?>
    </tr><tr>
    <?php }} ?>
    </tr>
</table>
Steve
$count should be renamed. The name "count" suggests that you would get that many cells. If $start isn't set to zero, you won't get a number of cells equal to $count.
Larsenal
good point Larsenal
Steve
+3  A: 
for (int i = 0; i < 22; i++)
{
    if(i % 5 == 4)
    {
        // this happens every 5th time through the loop
    }
}
Larsenal
A: 

Another variation:

int j=0;
for(int i = 0; i < 500; i++) 
{ 
    j++;
    if(j >= 5) 
    { 
        j = 0;
        //do your stuff here 
    } 
}

I'm old fashioned, I remember when division took a long time. With modern cpus it probably doesn't matter much.