While Loop in C# Language
In the world of programming, loops are a fundamental concept that allows you to execute a block of code repeatedly. Among the various types of loops available in
In the world of programming, loops are a fundamental concept that allows you to execute a block of code repeatedly. Among the various types of loops available in
while
loop is a simple yet powerful construct that helps you accomplish this task. In this post, we’ll explore the while
loop in C# and provide examples to illustrate its usage.
while
LoopA while
loop in C# is a control flow statement that repeatedly executes a block of code as long as a specified condition remains true. The syntax of a while
loop is as follows:
while (condition)
{
// Code to be executed while the condition is true
}
Here’s how it works:
condition
is a Boolean expression. As long as this expression evaluates to true
, the code block within the while
loop will continue to execute.condition
becomes false
, the loop terminates, and the program proceeds to the next line of code after the while
loop.while
LoopLet’s dive into a simple example to demonstrate how the while
loop works. We’ll create a program that prints numbers from 1 to 5 using a while
loop.
using System;
class Program
{
static void Main()
{
int counter = 1;
while (counter <= 5)
{
Console.WriteLine(counter);
counter++; // Increment the counter
}
Console.WriteLine("Loop finished!");
}
}
In this example, we initialize the counter
to 1 and use a while
loop to print the numbers from 1 to 5. The loop continues executing as long as counter
is less than or equal to 5. Inside the loop, we increment the counter
by 1 in each iteration. The program will output the following:
1
2
3
4
5
Loop finished!
It’s important to ensure that the condition within a while
loop eventually becomes false
. If the condition never becomes false
, you’ll create an infinite loop, which can lead to your program running indefinitely and potentially causing performance issues or crashes. To avoid infinite loops, make sure the condition in the loop will eventually change so that the loop can exit.
You can also use loop control statements like break
and continue
to control the flow of your while
loop. break
allows you to exit the loop prematurely, while continue
lets you skip the current iteration and move to the next one.
Subscribe to get the latest posts sent to your email.