math - How to take any number and get a number between 1-3 -


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 color.

I know that I can reset only one counter of every 3 loops, and I can use it to use the color I want - 1, 2, 3, reset, 1, 2, 3, reset etc. Is there an easy way to get current loop count, like 5 or 7, and 2? Or near 6 or 9 and get 3? Am I getting some simple math solutions about this?

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

arrayIndex = LoopCount% 3;

Basically it means that the number divides by 3 and gives me the remainder ... so this is equal to 0 1 2 0 1 2 0 1 2, etc ... < / P>

Edit:

If you are using a language that creates an array index on 1, you can do this:

  arrayIndex = LoopCount% 3 + 1;  

Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -