C++ Tutorials: Loops

In this tutorial we will be covering loops. This is going to be a shorter tutorial then all the others but much more necessary.

A loop is a a something that repeats until a condition is met or infinitely. There are two kinds of loops:

For

and 

While

While is more common but they are both used a lot.

They look like this:

Code

for(int i=0;i<10;i++)
{}

int i=0;
while(i<10)
{
i++;
}




Those two pieces of code are effectivly the same. The for loop looks better doesn’t it? Well for loops are generally used for that type of thing, 

While loops though are used where for loops look bad like so:

Code

for(;;;)
{
}

while(true)
{}




These two pieces of code are the same, they are both repeat indefinitely. the while loop looks better right?

so here is a good example:

Code


int main()
{
    while(true)
    {        cout << "this will go on forever" << endl;
    }
    return 0;
}




Now there is one special thing before we move on to the next tutorial:

endl

endl means end line and is defined as char endl = “n”;

so you can either use endl or n

In the Next tutorial we will be discussing input. We will also be discussing special types such as cerr.

What Do You Think on This ? Say Here