While Loops

Lesson 18
Author : Afrixi
Last Updated : February, 2023
C# - Programming Language
This course covers the basics of programming in C#.

In C#, a while loop is used to repeatedly execute a block of code as long as a particular condition is true. The general syntax for a while loop is as follows:

while (condition)
{
    // code to execute while condition is true
}

The condition is evaluated at the beginning of each iteration of the loop. If it’s true, the code inside the loop is executed. After the code is executed, the condition is evaluated again, and the process repeats until the condition becomes false.

Here’s an example of using a while loop to count from 1 to 10:


int i = 1;
while (i <= 10)
{
    Console.WriteLine(i);
    i++;
}

In this example, we’re declaring an integer variable i and initializing it to 1. Then we’re using a while loop to repeatedly execute the block of code inside the loop as long as i is less than or equal to 10. Inside the loop, we’re using Console.WriteLine() to output the value of i to the console, and then we’re incrementing i by 1 using the ++ operator. This loop will output the numbers 1 through 10 to the console.

We can also use a while loop to validate user input. For example, we can use a while loop to repeatedly prompt the user to enter a positive integer until they enter a valid input:


int num = 0;
while (num <= 0)
{
    Console.Write("Enter a positive integer: ");
    string input = Console.ReadLine();
    if (int.TryParse(input, out num) && num > 0)
    {
        Console.WriteLine("You entered: " + num);
    }
    else
    {
        Console.WriteLine("Invalid input, please try again.");
    }
}

In this example, we’re declaring an integer variable num and initializing it to 0. We’re then using a while loop to repeatedly prompt the user to enter a positive integer as long as num is less than or equal to 0. Inside the loop, we’re using Console.ReadLine() to read a line of input from the user, and then we’re using int.TryParse() to attempt to parse the input as an integer. If the input is a valid positive integer, we assign it to num and output a message to the console. Otherwise, we output an error message and repeat the loop. This loop will continue until the user enters a valid positive integer.