Mahmoud
Mahmoud

Reputation: 197

infinite loop in C#

This simple program take an input of integers and print them , but stop printing if it sees 60

        string input = string.Empty;
        int intValue = 0;
        int[] numbers = new int[5];

        for (int i = 0; i < 4; i++)
        {
            input = Console.ReadLine();
            if (int.TryParse(input, out intValue))
                numbers[i] = intValue;
        }

        for (int i = 0; i < numbers.Length; i++)
        {
            while (numbers[i] != 60)
            {
                Console.WriteLine(intValue);
            }
        }

the program go on an infinite loop after the 4th input like that Input: 1 2 3 4 4 4 4 4 4 ........ and so on

and i don't know the reason .... ^_^

Upvotes: 0

Views: 2103

Answers (2)

Javadotnet
Javadotnet

Reputation: 125

string input = string.Empty;

    int intValue = 0;
    int[] numbers = new int[5];

    for (int i = 0; i < 4; i++)
    {
        input = Console.ReadLine();
        if (int.TryParse(input, out intValue))
            numbers[i] = intValue;
    }

    for (int i = 0; i < numbers.Length; i++)
    {
        /*while (numbers[i] != 60)*/
        if (numbers[i] != 60)  // it should be if condition, while statement made it infinite
        {
            Console.WriteLine(intValue);
        }
    }

Upvotes: 0

bhuang3
bhuang3

Reputation: 3633

while (numbers[i] != 60)
{
    Console.WriteLine(intValue);
}

should be:

if (numbers[i] != 60)
{
    Console.WriteLine(intValue);
}

Upvotes: 5

Related Questions