tags:

views:

199

answers:

7

I have three colors in an array, array('blue', 'red', 'green'), and in my loop, I want to be able to print blue, red, green, blue, red, green.

I know that I could just reset a counter every 3 loops, and use that to find the color I want - 1, 2, 3, reset, 1, 2, 3, reset, etc. But is there a simple way to pass it the current loop count, like, 5 or 7, and get 2? Or pass 6 or 9 and get 3? Am I missing some simple math solution to this?

+12  A: 

What you're looking for is the modulo operator '%';

arrayIndex = loopCount % 3;

basically this means divide the number by 3 and give me the remainder...so it'll equal 0 1 2 0 1 2 0 1 2, etc...

EDIT:

If you're using a language that starts array indexes at 1 you can do:

arrayIndex = loopCount % 3 + 1;
McAden
This is right, I lied with my "+1" answer below.
DreadPirateShawn
+1  A: 

use modular arithmetic, 5 mod 3 = 2, 6 mod 3 = 0, 7 mod 3 = 1, etc... and then add 1 if your list is 1 based instead of 0 based.

EDIT: The modulo operator can be different depending on what language you are using. Wikipedia lists most of them.

rmoore
+1  A: 

You seem to be assuming that math is involved.

while (true) {
    foreach (var color in colors) {
        Console.WriteLine(color);
    }
}

Written in C# since you didn't indicate what language or platform you're using.

John Saunders
+2  A: 

You want "mod".

If you start your loop count at zero, this would mean:

(loopCount % 3) + 1

DreadPirateShawn
+1  A: 

given array['blue', 'red', 'green'] to get what you want, do

array[number mod 3]
codemeit
+1  A: 

Here is a working C# example:

using System;

class Program
{
    static void Main()
    {
     int iterations = 5;

     String[] colors
      = new String[] { "blue", "red", "green" };

     for (int i = 0; i < colors.Length * iterations; i++)
     {
      Console.WriteLine(colors[i % colors.Length]);
     }
    }
}
Andrew Hare
+2  A: 

Instead of resetting the counter you could compute the remainder of dividing the current count by the total number of elements in your array (that is, use the mod function).

For example,

int i;
char *colors[] = {"red", "green", "blue"};

for (i = 0; i < 100; i++)
        printf("%s\n", colors[i % 3]);
jmbr