5 Questions
What is the condition for the while loop to continue executing in the basic example?
i is less than 5
What is the purpose of the while loop in the reading user input example?
To prompt the user to enter their name until they enter a valid name
What happens to the variable seconds in each iteration of the while loop in the simulating a timer example?
It is decremented by 1
What is the purpose of the System.Threading.Thread.Sleep(1000) line in the simulating a timer example?
To wait for 1 second
What is the output of the basic example when i is equal to 4?
The value 4 will be displayed
Study Notes
While Loop Examples
The while loop is a fundamental control flow statement in C# that allows code to be executed repeatedly while a certain condition is true. Here are some examples of using while loops:
Basic Example
- Initialize a variable
i
with a value of 0. - The loop continues to execute as long as
i
is less than 5. - In each iteration,
i
is incremented by 1.
int i = 0;
while (i < 5)
{
Console.WriteLine(i);
i++;
}
Reading User Input
- Prompt the user to enter their name.
- Continue to prompt the user until they enter a non-empty string.
string name;
while (true)
{
Console.Write("Enter your name: ");
name = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(name))
{
break;
}
Console.WriteLine("Please enter a valid name.");
}
Simulating a Timer
- Initialize a variable
seconds
with a value of 10. - The loop continues to execute as long as
seconds
is greater than 0. - In each iteration,
seconds
is decremented by 1.
int seconds = 10;
while (seconds > 0)
{
Console.WriteLine($"Time remaining: {seconds} seconds");
seconds--;
System.Threading.Thread.Sleep(1000); // wait for 1 second
}
Console.WriteLine("Time's up!");
While Loop Examples
Basic Example
- Initialize a variable
i
with a value of 0, and the loop continues to execute as long asi
is less than 5. - In each iteration,
i
is incremented by 1, and the current value ofi
is printed to the console.
Reading User Input
- Continuously prompt the user to enter their name until a non-empty string is entered.
- If an empty string is entered, the user is prompted again, and an error message is displayed.
Simulating a Timer
- Initialize a variable
seconds
with a value of 10, and the loop continues to execute as long asseconds
is greater than 0. - In each iteration,
seconds
is decremented by 1, and the remaining time is printed to the console. - The program waits for 1 second between each iteration using
System.Threading.Thread.Sleep(1000)
. - When
seconds
reaches 0, a "Time's up!" message is displayed.
Examples of using while loops in C# programming language, including basic examples and reading user input.
Make Your Own Quizzes and Flashcards
Convert your notes into interactive study material.
Get started for free