c sharp Logo

C# While Loop


While Loops

The while loop is a control flow structure in C# that repeatedly executes a block of code as long as a specified condition is true. The syntax of a while loop is:

while (condition) {

  // Code block to execute repeatedly

}

 

Example

The following code prints the numbers from 1 to 5:

int number = 1;

 

while (number <= 5) {

  Console.WriteLine(number);

  number++;

}

 

Do-While Loops

The do-while loop is another control flow structure that executes a block of code at least once, and then repeatedly executes the block as long as a specified condition is true. The syntax of a do-while loop is:

do {

  // Code block to execute at least once

} while (condition);

 

Example

The following code repeatedly asks the user for a number until they enter a valid positive integer:

int input;

 

do {

  Console.Write("Enter a positive integer: ");

  input = int.Parse(Console.ReadLine());

} while (input <= 0);

 

Console.WriteLine("You entered: " + input);

 

Key Differences between While and Do-While Loops

The primary difference between while and do-while loops is the order of condition evaluation. In a while loop, the condition is evaluated before the code block is executed, so there is a possibility that the code block may not be executed at all if the condition is initially false. In a do-while loop, the condition is evaluated after the code block is executed, so the code block is guaranteed to be executed at least once.

Choosing between While and Do-While Loops

The choice between using a while loop or a do-while loop depends on the specific situation. If you want to execute the code block at least once, regardless of the condition, then use a do-while loop. If you want to check the condition before executing the code block, then use a while loop.

Conclusion

Both while and do-while loops are valuable tools for controlling the flow of execution in C# programs. They allow programmers to repeatedly execute code blocks based on conditions, enabling tasks such as iterating over collections, processing input, and simulating repetitive processes.