c-sharp
  1. c-sharp-while-loop

C# While Loop

Syntax

while (condition)
{
   // statements to be executed repeatedly while the condition is true
}

Example

int i = 0;
while (i < 5)
{
    Console.WriteLine(i);
    i++;
}

Output

0
1
2
3
4

Explanation

In C#, a while loop is used to execute a block of code repeatedly while a certain condition is true. The code inside the while loop will continue to execute as long as the condition evaluates to true. If the condition is initially false, the code inside the loop will not execute.

The while loop is structured with the keyword "while" followed by the condition to be evaluated inside of parentheses. Then, inside of curly braces, the statements to be repeated are written.

Use

The while loop is useful for executing code repeatedly based on certain conditions that may or may not be known in advance. This can be helpful in situations such as user input validation, data processing, and iterating through collections.

Important Points

  • The condition in a while loop must be a Boolean expression.
  • If the condition is never true, the code inside the loop will never execute.
  • It is important to make sure that the condition will eventually become false in order to exit the loop.

Summary

In C#, the while loop is used for executing a block of code repeatedly while a certain condition is true. The loop consists of the "while" keyword followed by a Boolean expression in parentheses, and the code to be repeated inside of curly braces. The while loop can be used for user input validation, data processing, and iterating through collections.

Published on: