I have question example:
int A = 20; int B = 10, int C = 40, int D = 5;
How to make its looping number from A -> B -> C -> D ->
and back start from A again?
What I know something like this:
var arr1 = new[] { A, B, C, D };
Random rnd = new Random();
var Result = arr1[rnd.Next(arr1.Length)];
but using random will make looping random value sometimes can be like
A -> A -> C -> A -> D
What I want is looping step by step like from A -> B -> C -> D ->
and back start from A again. Or I meant Being 20 -> 10 -> 40 -> 5 ->
then start again from 20
I hope your understand my question because my English is bad sorry and thanks!
You wouldn't have a random in there if you wanted A,B,C,D,A...
You simply want to ensure that you reset the index to 0 when it reaches 3, for an array with 4 items inside
The simplest way to do this is to use the modulo operator %
, which gives the remainder number left over after a division operation:
for(int x = 0; x < 1000; x++){
var y = x % arr1.Length;
Console.WriteLine(arr1[y]);
}
You set the 1000 to whatever number of times you actually want to cycle around for; in this case the code will print out the values for A,B,C,D in a cycle 250 times (1000 loops printing one of four items means each item prints out 250 times)
Because %
is a remainder it will never exceed the divisor (the value being divided by), minus one. In this case the divisor is 4, so the remainder will never exceed 3. This is also the maximum index available in an array of four items:
0%4 == 0
1%4 == 1
2%4 == 2
3%4 == 3
4%4 == 0 //we're back to the start
5%4 == 1
And so on. It's handy to remember that any positive number, modulo array.Length
will not go out of the array. It also means, because it works off array.Length, that you don't have to worry about how many items are in the array - could be 10, a million etc, the code will adjust automatically to cycle round no matter how big the array is
Just be careful with negative numbers, because the result of a negative number modulo is negative (-10 % 4 is -2)