0

I can't quite figure it out how to loop through string array after the first initial loop has been done.

My code right now is:

    string[] assignments = new string[] {"A", "B", "C", "D", "E", "F"};

    Array.Resize<string>(ref assignments, 99);
    for (int i = 0; i < 99; i++)
    {
    Console.WriteLine(assignments[i]);
    }

However, it seems that Resizing the array doesn't accomplish much, since arrays values after the 6th value is non-existant. I need it to keep looping more then once: A B C D E F A B C D E F ... and so on, until the limit of 99 is reached.

Aryan Firouzian
  • 1,940
  • 5
  • 27
  • 41
Ralfs R
  • 77
  • 1
  • 8

4 Answers4

6

Use the mod operator.

string[] assignments = new string[] {"A", "B", "C", "D", "E", "F"};
for (int i = 0; i < 99; i++)
{
    Console.WriteLine(assignments[i % assignments.Length]);
}

.net fiddle

Igor
  • 60,821
  • 10
  • 100
  • 175
2

You can use the modulus operator which "computes the remainder after dividing its first operand by its second."

void Main()
{
    string[] assignments = new string[] {"A", "B", "C", "D", "E", "F"};

    for (int i = 0; i < 99; i++)
    {
        var j = i % 6;
        Console.WriteLine(assignments[j]);
    }
}

0 % 6 = 0
1 % 6 = 1
...
6 % 6 = 0
7 % 6 = 1   
... etc.
Zeph
  • 1,728
  • 15
  • 29
2

The obligatory LINQ solution, this extension comes in handy:

public static IEnumerable<T> RepeatIndefinitely<T>(this IEnumerable<T> source)
{
    while (true)
    {
        foreach (var item in source)
        {
            yield return item;
        }
    }
}

Now your task is very easy and readable:

var allAssignments = assignments.RepeatIndefinitely().Take(99);

You can use a foreach-loop with Console.WriteLine or build a string:

string result1 = string.Concat(allAssignments);
string result2 = string.Join(Environment.NewLine, allAssignments)
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • I very much like this. However could it be considered a tad dangerous that the call to repeat indefinitely on its own will crash when it's evaluated? – Dave Oct 30 '17 at 14:18
  • @Dave: of course it's a bit dangerous, if you f.e. append `ToList` without a filter (f.e `Where` or `Take`) you will get an `OutOfMemoryException`. But since the name is pretty clear you should know what will happen if you try to take an infinite number of items ;-) – Tim Schmelter Oct 30 '17 at 14:20
0

How about using mod

string[] assignments = new string[] { "A", "B", "C", "D", "E", "F" };

        for (int i = 0; i < 99; i++)
        {
            Console.WriteLine(assignments[i%6]);
        }
wctiger
  • 921
  • 12
  • 22