Reb
Reb

Reputation: 3

C# loop going back and forth

I'd like to make a for loop that goes backwards after it reaches the end. So when "i" reaches 10, instead of "i++" it should do "i--".

I've looked online for a little bit and couldn't find anything in C#. There's this post here, yet it's in JavaScript. I've rarely coded in JavaScript before, so I'm not sure how to translate that code into C# (if that even is possible).

I've successfully achieved this using the code below, yet it's lacking in the "readability" department. It also requires an extra variable, which I don't think is the most elegant solution. Here's the code that I've written:

static void Main(string[] args)
        {
            bool reverse = false;

            for(int i = 0; i <= 10;)
            {
                Console.WriteLine(i);
                if(i == 10) reverse = true;
                if(i == 0) reverse = false;
                if(reverse == false) i++;
                if(reverse == true) i--;
                
                // Slow down the output
                Thread.Sleep(20);
            }

        }

Again, this code works fine, yet I'm looking for a better solution than this mess.

Thanks in advance!

Upvotes: 0

Views: 237

Answers (1)

Klaus G&#252;tter
Klaus G&#252;tter

Reputation: 11977

As small readability improvement I would suggest to change from the boolean flag to an integer increment value:

        int increment = 1;

        for (int i = 0; i >= 0 && i <= 10; i += increment)
        {
            Console.WriteLine(i);
            if (i == 10) increment = -1;
            else if (i == 0) increment = 1;
        }

Upvotes: 2

Related Questions