i am very new to c# and while loops. Does anyone know how to stop it? it keeps printing the first if statement. Here is the code:
const int Year = 400;
const int LeapYear = 4;
const int NoLeapYear = 100;
int input = 0;
input = int.Parse(Console.ReadLine());
while (input != 0)
{
Console.WriteLine("Enter a number: ");
if (input > 0 && input % LeapYear == 0 || input % Year == 0)
{
Console.WriteLine($"{input} is a leap year.");
}
if (input > 0 && input % NoLeapYear != 0)
{
Console.WriteLine($"{input} is not a leap year.");
}
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
if (input == 0)
{
Console.WriteLine("End of program");
}
}
CodePudding user response:
You have to read the input inside the while loop:
const int Year = 400;
const int LeapYear = 4;
const int NoLeapYear = 100;
int input = -1; // initialize to something different than zero, to enter the while loop (or use do while loop instead of while loop)
while (input != 0)
{
Console.WriteLine("Enter a number: ");
input = int.Parse(Console.ReadLine()); // you were missing this line
if (input > 0 && input % LeapYear == 0 || input % Year == 0)
{
Console.WriteLine($"{input} is a leap year.");
}
if (input > 0 && input % NoLeapYear != 0)
{
Console.WriteLine($"{input} is not a leap year.");
}
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
if (input == 0)
{
Console.WriteLine("End of program");
}
}
Consider using a do while loop in this case.
CodePudding user response:
If you are using loop just and break to true statement It will breaks it
CodePudding user response:
while (input != 0) {
conditions;
break; // Breaks the loop
}
Use the break;
keyword to stop any loop in C# not just C# in many languages also break is used to stop loops
Or,
Satisfy the condition to opposite of what you have it will break/stop the loop
CodePudding user response:
use break
(https://www.w3schools.com/cs/cs_break.php)
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i ;
if (i == 4)
{
break;
}
}