Jump to content

Problem with "while"

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
noxrawr

noxrawr

    Newbie

  • Members
  • PipPip
  • 23 posts
Can anyone tell me why this script keeps running indefinitely?

static void Main(string[] args)

        {

            int number = 0;

            bool limit = (number < 100);

            while (limit)

            {

                Console.WriteLine("the number is " + number);

                number++;

                

            }

        }

As far as I understand it should stop at 100 but for some reason it doesnt.

#2
CommittedC0der

CommittedC0der

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,565 posts
That's because "limit" is always 0 it never changes its value, try this:
int number = 0;
            bool limit = (number < 100);
            while (limit)
            {
                Console.WriteLine("the number is " + number);
                number++;
               [COLOR=Red] limit = (number < 100);[/COLOR]
[COLOR=Green]//Or you could use this code instead: limit++;[/COLOR]

            }
            Console.ReadKey();
You need to re-assign limits value to the number value, so limit it is going up with the number value and equaling zero the whole time. :)
A man can be defined by what he does when no one is looking.
Science is only an educated theory, which we cannot disprove.

#3
noxrawr

noxrawr

    Newbie

  • Members
  • PipPip
  • 23 posts
so I see, cheers.

#4
Davide

Davide

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 506 posts
while (i<100)
{
                Console.WriteLine("the number is " + number);
                i++;
}

Are you a newbie programmer trying to learn C#? Check out my small tutorial: Visual C# Programming Basics

#5
lobo521

lobo521

    Learning Programmer

  • Members
  • PipPipPip
  • 57 posts
To avoid problems like that use for loop. It's easier to read your code.

for (int i = 0; i < 100; i++)
{
    Console.WriteLine("the number is " + i);
}