Search code examples
c#arraysloopsfor-looprotation

In C#, I'm trying to iterate strings in single loop, how?


I'm trying to achieve this output:

LOWEST LOW MEDIUM HIGH HIGHEST HIGHEST HIGH MEDIUM LOW LOWEST

I know there are many ways to do it, but I'm trying it in single loop, is it achievable?

My code is basically like this:

class Program {
    static void Main()
    {
        string[] phases = ["LOWEST", "LOW", "MEDIUM", "HIGH", "HIGHEST"];
        int fullRotation = (phases.Length - 1) * 2;
        for (int i = 0; i <= fullRotation; i++)
        {
            int index;
            if (i <= (phases.Length - 1))
            {
                index = i;
            }
            else
            {
                index = fullRotation - i;
            }

            Console.Write(phases[index] + " ");
        }
    }
}

I'm getting:

LOWEST LOW MEDIUM HIGH HIGHEST HIGH MEDIUM LOW LOWEST

Solution

  • Your loop has fullRotation + 1 (i.e. (phases.Length - 1) * 2 + 1) iterations because of the <= comparison. But it should have one more iteration than that (i.e. (phases.Length) * 2).

    I would do:

    int fullRotation = phases.Length * 2;
    for (int i = 0; i < fullRotation; i++)
    

    This loop now has phases.Length * 2 iterations. But the calculation in the else branch is now off-by-1, so you should also subtract 1:

    else {
        index = fullRotation - i - 1;
        //                      ^^^^
    }