Trong Tin Nguyen
Trong Tin Nguyen

Reputation: 21

Is it possible to loop over incremental variable names?

Supposing I have some variables with names : daywinner1 , daywinner2 , daywinner3... How can I loop over these variables by increasing their incremental components ???

I've tried but I can't achieve it

My code :

        string[][] olympia =
        {
            new string[]{"a","b","c" },
            new string[]{"d","e"},
            new string[]{"f","g","h","j","k"}
        };
        int daywinner1 = int.Parse(Console.ReadLine());
        int daywinner2 = int.Parse(Console.ReadLine());
        int daywinner3 = int.Parse(Console.ReadLine());
        for (int i = 0; i < olympia.Length; i++)
        {
            Console.WriteLine(olympia[][]);
        }    

Upvotes: 0

Views: 102

Answers (1)

Erdrik Ironrose
Erdrik Ironrose

Reputation: 171

It is not possible to iterate over variable names in this way, as each variable is a discrete, separate box. There is no relationship between "daywinner1", "daywinner2" and "daywinner3" in the code.

You could have named them "distance", "height" and "width", or "red, blue, green". There is no way for the compiler to know what their relationship with each other is, or what order they should be in.

However, you could instead create an array, where each element contains the value you want in an explicit order.

For example:

int[] daywinners = new int[3];
daywinners[0] = int.Parse(Console.ReadLine());
daywinners[1] = int.Parse(Console.ReadLine());
daywinners[2] = int.Parse(Console.ReadLine());

You can then iterate over the array of daywinners like so:

foreach (var daywinner in daywinners) {

}

I recommend learning more about data structures.

Upvotes: 5

Related Questions