Monday, October 11, 2010

Understanding the Loop constructs in C sharp

The following loop constructs are supported by C#.

  • The While loop.
  • The do…while loop.
  • The for loop.
The While loop: - The while loop construct is used to execute a block of statements for a definite number of times, depending on a condition. The while statement always checks the condition before executing the statements within the loop. When the execution reaches the last statement in the while loop, the control is passed back to the beginning of the loop. If the condition still holds true, the statements within the loop are executed again. The execution of the statements within the loop continues until the condition evaluates to false.

syntax of while loop.


Example of while loop

using System;

class variable
static void Main(string[] args)
int var;
var = 100;
while(var gt 200)
System.Console.WriteLine("Value of variable is: {0}", var);
var= var+10;

Note: - The preceding code creates an integer variable var and assigns the value 100 to it. The while statements checks whether the value of var is lower than 200. If the condition evaluates to true, the statements within the while loop are executed. This process continues until the value of var becomes greater than or equal to 200.

The result is displayed below with while loop .

Value of variable is: 100
Value of variable is: 110
Value of variable is: 120
Value of variable is: 130
Value of variable is: 140
Value of variable is: 150
Value of variable is: 160
Value of variable is: 170
Value of variable is: 180
Value of variable is: 190

C Sharp Statements Related Contents.

How to use do…while loop in C #.
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