4
Answers

piece of code does not work

saman hamidi

saman hamidi

11y
1.1k
1
Why does this piece of code does not work?
it is supposed to be a "random walk". and I should not be using any methods or classes. just branching, looping and arrays.
I have no errors from the compiler but when I try to run the code console appears and then disappears before I can do anything.

static void Main(string[] args)
        {
            Random randomObject = new Random();
            int randomDirection;
            int row=1;
            int col=1;
            while (true)
            {
                int n;
                int row = 1;
                int col = 1;
                Console.WriteLine("Enter the number of steps: ");
                n = Convert.ToInt32(Console.ReadLine());
                for (int i = 0; i < n; i++)
                {
                    randomDirection = randomObject.Next(1, 5);
                    if (randomDirection == 1 && row > 0 && row < 10)
                        row++;
                    else if (randomDirection == 2 && row > 0 && row < 10)
                        row--;
                    else if (randomDirection == 3 && col > 0 && col < 10)
                        col++;
                    else if (randomDirection == 4 && col > 0 && col < 10)
                        col--;
                    else
                        i--;
                }
                Console.WriteLine("You have walked in row: " + row);
                Console.WriteLine("You have walked in col: " + col);
                Console.WriteLine("");
            }
            Console.ReadKey();
        }

Answers (4)