What is Do/While Loop In C#?

3 mins read

A loop generally means something continuous and here we discuss while loop in C# and everything you should understand about it as a programmer using C#.

What is a Loop In C#?

A loop statement allows us to execute a statement or a group of statements multiple times depending on the result of the condition to be evaluated to execute statements. Loops are handy because they save time, reduce errors, and they make code more readable.

While Loop in C#

In C#, a while loop would always execute a target statement as long as the given condition is true. If the given condition is not true, it won’t execute a target statement.

Is there a While Loop in C#?

Yes, there is a while loop in C#.

What is Syntax of While Loop?

Below is the Syntax of while loop in C#

According to Tutorials Point, at this point, the statement is true and could be a single/ or multiple statement (s) while the given condition may be any expression. True here is also expected to be a nonzero value and the loop continues as the given condition is true.

While Loop In C#

What is the Function of While Loop In C# ?

The while  loop loops through a block of code as long as a specified condition is true.

Code sample:

In the example below, the code in the loop will run, over and over again, as long as a variable i is less than 5:

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end.

What is the Function of Do/While Loop In C# ?

The do/while  loop is a variant of the while  loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Code sample

In the example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested:

Note: Do not forget to increase the variable used in the condition, otherwise the loop will never end.

Leave a Reply

Your email address will not be published.