Loop Constructs in C#

We have three types of loop constructs
1. while.
2. do...while .
3. for.

  • while loop
    1. This construct is generally used to execute a block of statements for a definite number of times, depending on the condition.
    2. while statements checks the condition before executing the statements within the loop.
    3. When the execution reaches the last line of the block the control is transferred to the condition of while and if the condition is satisfied then the statements are executed again and when the condition sets to false it comes out the loop.
syntax:
while(expression)
{
statements;
}
  • do..while loop
1. Both Iterate until the specified loop condition becomes false.
2. however, in do...while loop , the body of the loop is executed at least once and the condition is checked for next subsequent iterations.
3. The do...while loop construct is similar to the while loop constructs.

syntax:
do
{
statements;
}while(expression);

example:

int var=10;
do
{
Console.WriteLine("value of var is :{0}",var);
var=var+10;
}
while(var<20);
  • for loop
  1. for loop is used to execute a block of statements for a specific number of times.
  2. Here the main difference between for and while is mainly in syntactical format. The syntax used for loop is ......
Syntax:
for(initialization; condition; increment/decrement)
{
statements;
}
example:

for(int i=1;i<=10;i++) { Console.WriteLine("{0}",i); }
Note:
We can follow different syntax's for for loop
for(; ;)
{
statements;
}

        0 Comments:

        Post a Comment



        Newer Post Older Post Home