Course Content
C# Tutorial
About Lesson

Looping structures (for, while, do-while)

Looping structures in C# are essential components for executing repetitive tasks efficiently. They allow developers to iterate through a set of instructions multiple times until a specific condition is met. In C#, there are primarily three types of looping structures: for, while, and do-while. Let’s delve into each of these constructs to comprehend their functionalities and usage.

The ‘for’ Loop

The for loop in C# is commonly used when the number of iterations is known beforehand. Its syntax comprises three essential components:

for (initialization; condition; increment/decrement)
{
// Code block to be executed
}

Here’s an example demonstrating the for loop:

for (int i = 0; i < 5; i++)
{
Console.WriteLine("Value of i: " + i);
}

In this example, the loop initializes i to 0, executes the code block as long as i is less than 5, and increments i by 1 in each iteration.

The ‘while’ Loop

The while loop is used when the number of iterations is not precisely known beforehand but depends on a certain condition. Its structure is as follows:

while (condition)
{
// Code block to be executed
}

Consider the following while loop example:

int num = 0;
while (num < 5)
{
Console.WriteLine("Value of num: " + num);
num++;
}

In this case, the loop continues to execute as long as num is less than 5. The value of num increments by 1 in each iteration until the condition is false.

The ‘do-while’ Loop

The do-while loop is similar to the while loop, except that it always executes the code block at least once before checking the condition for further iterations. Its structure looks like this:

do
{
// Code block to be executed
} while (condition);

Here’s an example illustrating the do-while loop:

int count = 0;
do
{
Console.WriteLine("Count: " + count);
count++;
} while (count < 3);

This loop will execute the code block first and then check the condition. If the condition is true, it will continue executing the block until the condition becomes false.