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.

1
  • Do you want your array to contain those repeated items? Commented Oct 30, 2017 at 14:01

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

@DmitryBychenko - fair enough. Updated.
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.

Comments

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)

2 Comments

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: 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 ;-)
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]);
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.