Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   Iteration Statements (http://www.go4expert.com/articles/iteration-statements-t2304/)

Programmer.Nick 20Dec2006 20:34

Iteration Statements
 

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 21Dec2006 11:19

Re: Iteration Statements
 
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 21Dec2006 12:02

Re: Iteration Statements
 
Quote:

Originally Posted by pradeep
Can't we write the code like this?

There will be difference in the output

pradeep 21Dec2006 12:12

Re: Iteration Statements
 
How and why will it be different?

shabbir 21Dec2006 13:02

Re: Iteration Statements
 
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.


All times are GMT +5.5. The time now is 03:23.