Home > Software engineering >  When entering zero the while loop gives the wrong consolewriteline
When entering zero the while loop gives the wrong consolewriteline

Time:09-29

i have made a while loop to check if the input year is a leap year or not. This works perfectly, but when entering a '0' I always get the "0 is a leap year.". The purpose of 0 is to stop the while loop. It shouldnt print anything.

const int Year = 400;
    const int LeapYear = 4;
    const int NoLeapYear = 100;
    int input = 0;
    bool numberIsZero = false;

    while (!numberIsZero)
    {
        Console.Write("Enter a number: ");
        input = int.Parse(Console.ReadLine());
        if (input == 0)
        {
            numberIsZero = true;

        }
        if (input < 0)
        {
            Console.WriteLine("Year must be positive!");
        }
        else if (input > 0 && input % LeapYear == 0 || input % Year == 0) // input groter dan 0 EN result moet na berekening van 4 op 0 komen OF berekening delen door 400 op 0.
        {
            Console.WriteLine($"{input} is a leap year.");
        }

       else 
        {
            Console.WriteLine($"{input} is not a leap year.");
        }
      
      
    }

CodePudding user response:

The/a while loop will not magically stop because its condition has changed. The condition is only checked once every iteration before the loop's body is entered.

You have two options: if/else to only conditionally execute the second part of the loop's body or break to abort the loop early.

Option 1:

while (!numberIsZero)
{
    Console.Write("Enter a number: ");
    input = int.Parse(Console.ReadLine());
    if (input == 0)
    {
        numberIsZero = true;
    }
    else // <-- else here
    {
      if (input < 0)
      {
        Console.WriteLine("Year must be positive!");
      }
      else if (input > 0 && input % LeapYear == 0 || input % Year == 0)
      {
        Console.WriteLine($"{input} is a leap year.");
      }
      else 
      {
        Console.WriteLine($"{input} is not a leap year.");
      }
    }
  } 
}

Option 2:

while (!numberIsZero)
{
    Console.Write("Enter a number: ");
    input = int.Parse(Console.ReadLine());
    if (input == 0)
    {
        numberIsZero = true;
        break; // <-- terminates loop
    }

    if (input < 0)
    {
        Console.WriteLine("Year must be positive!");
    }
    else if (input > 0 && input % LeapYear == 0 || input % Year == 0)
    {
        Console.WriteLine($"{input} is a leap year.");
    }
    else 
    {
        Console.WriteLine($"{input} is not a leap year.");
    }
}
  • Related