Why is the while loop the loop endless?

I want to execute the contents of the loop a maximum of 3 times, and every time the program runs, I want it to create a different number. So the first run can be 2, then 3, then 1, then 2, etc.

Here is the code I wrote:

       int i = new Random().Next(3);
        while (i <= 3)
        {

            Console.WriteLine("Hello World");

            i--;
        }**

However, this ends with an endless loop. Can someone help me understand what I'm doing wrong?

THANKS!

+4
source share
4 answers

You always decrease the variable, so it will always be less than 3

+3
source

i will always be less than 3 ... until Int.MinValue - 1 (overflow) hits.

+1
source

, ,

int i = new Random().Next(3);

while (i>0 && i <= 3)
    {

        Console.WriteLine("Hello World");

        i--;
    }**
+1

I think if you change the code to say “i ++” instead of “i--”, you will get the result you were looking for.

int i = new Random().Next(3);
        while (i <= 3)
        {

            Console.WriteLine("Hello World");

            i++;
        }**
+1
source

Source: https://habr.com/ru/post/1532594/


All Articles