Iteration Statements

Programmer.Nick's Avatar author of Iteration Statements
This is an article on Iteration Statements in C#.

Introduction



Iteration Statements are often known as looping, and they run many times while specific condition is true. I would try to explain some of them here. The lesson is for a begginer, and I guess that everyone need to know them.

While



The While loop function used and while the condition is true, the loop statement executed.
the genral form of while loop:

Code:
 
while (Boolean exception)
         statement or block of statements
and here is an example of a program, that time the value of i between 0 to 20:

Code: CSharp
using System;

class Program
{
    static void Main(string[] args)
    {
        int i;
        i=0;
        while (i < 20)
        {
            Console.WriteLine(i);
            i++;
        }
    }
}
so, know that whe knows what is the While loop statement is lets go for anothe statment of loop.

Do...While



The do while is exactly as the While loop, and its run while the condition is true, and when the condition is true the compiler goes to the do block statement, and he runs it.

The genral Form OF the Do....while:

Code:
do
        statement or a block of statement
while(booleans expression);
and here is an example
Code: CSharp
using System;

class Program
{
    static void Main(string[] args)
    {
        int i;
        i=0;
        do
        {
            Console.WriteLine(i);
            i++;
        }while(i<20);
    }
}
In this line of codes , the compiler do the same thing he done at the while Program.
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Can't we write the code like this?

Code: CSharp
using System;

class Program
{
    static void Main(string[] args)
    {
        int i;
        i=0;
        while (i++ < 20)
            Console.WriteLine(i);
    }
}
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by pradeep
Can't we write the code like this?
There will be difference in the output
pradeep's Avatar, Join Date: Apr 2005
Team Leader
How and why will it be different?
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Quote:
Originally Posted by pradeep
How and why will it be different?
Your code will print 1-20 and the sample would 0-19.
You should use i++ in WriteLine function instead.