Thursday, October 14, 2010

How to use do…while loop in C #.

The do…while loop construct is similar to the while loop construct. Both iterate until the specified loop condition becomes false. However, in the do…while loop, the body of the loop is executed at least once and the condition is evaluated for subsequent iterations.
Other words, The do...while loop always runs its body once. After its first run, it evaluates its condition to determine whether to run its body again. If the condition is true, the body executes. If the condition evaluates to true again after the body has ran, the body executes again. When the condition evaluates to false, the do...while loop ends.

The syntax of the do…while loop.

do
{
Statements;
}
While (conditions);

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace @do._.while_loop
{
class Program
{

static void Main(string[] args)
{
int var;
var = 100;
do
{
Console.WriteLine("Value of var:" + var);
var = var + 15;
}
while (var gt 200);
Console.ReadLine();
}
}
}
Note: - The condition is checked after the statements in the do…while loop structure is executed. Therefore, the statements within the do…while loop are executed at least once, regardless of whether the condition evaluates to true or false.

The output is displayed below with do... while loop .

Value of var: 100
Value of var: 115
Value of var: 130
Value of var: 145
Value of var: 160
Value of var: 175
Value of var: 190




C Sharp Statements Related Contents.

Understanding the while Loop constructs in C sharp.
Understanding the for loop in c sharp.
Understanding the Switch… case construct in C sharp.
if...else construct in c sharp.

No comments:

Recent Posts