WHILE Loops
When to Use WHILE Loops
Use WHILE loops when you need to keep going until something happens.
Perfect for: Counting until target reached, asking until correct answer, adding until total is enough, repeating until user says stop.
Example 1: Count to 5
Click to view code
Example 2: Keep Asking Until User Says "yes"
Click to view code
Example 3: Add Numbers Until Total Reaches 10
Click to view code
Example 4: Print 4 Stars
Click to view code
Example 5: Keep Doubling Until Over 50
Click to view code
Example 6: Validate Team Name (Not Empty)
Click to view code
Example 7: Validate Number of Bricks (1 to 1000)
Click to view code
bool isValidNumberOfBricks = false;
int numberOfBricks = 0;
string numberBriksInput = Console.ReadLine();
while (!isValidNumberOfBricks)
{
if (!int.TryParse(numberBriksInput, out numberOfBricks) || numberOfBricks <= 0 || numberOfBricks > 1000)
{
Console.WriteLine("Please enter a valid positive integer for the number of bricks.");
numberBriksInput = Console.ReadLine();
}
else
{
isValidNumberOfBricks = true;
}
}
Example 8: Validate Time Taken (Greater Than 0)
Click to view code
bool isValidTimeTaken = false;
int timeTaken = 0;
string timeTakenInput = Console.ReadLine();
while (!isValidTimeTaken)
{
if (!int.TryParse(timeTakenInput, out timeTaken) || timeTaken <= 0)
{
Console.WriteLine("Please enter a valid positive integer for the time taken.");
timeTakenInput = Console.ReadLine();
}
else
{
isValidTimeTaken = true;
}
}
Example 9: Validate Judge Score (0 to 10)
Click to view code
bool isValidScore = false;
float score = 0;
string scoreInput = Console.ReadLine();
while (!isValidScore)
{
if (!float.TryParse(scoreInput, out score) || score < 0 || score > 10)
{
Console.WriteLine("Please enter a valid score between 0 and 10.");
scoreInput = Console.ReadLine();
}
else
{
isValidScore = true;
}
}