You are here

Loops For Beginners

Hey you beginners, in this tutorial i will cover, loops(for, do/while, and while). If you dont have a clue about what i just said keep reading, and all questions will be answered.

Loops:
for loop:
The sytax for a for loop is

.     1         2         3

for( x = 0; x < 10; x++ )
{
statements;
}

Now to Explain it the for loop
1: This its the starting point; x = 0 at the beginning
2: This is the number in which it will be looping till; the loop will end at 9
3: This is how x will be incermented or decremented; you can put x++, x- -, x = x + 2, ect....

Statements: It can be anything you want to have done repeatedly,
ex: cout<< x << endl;
Using that withe the example will output 0 - 9, because the stoping point is set to less than 10 so 9 is the closest number w/o equaling it.

Put it all together, sample program using for loop:

#include &ltiostream.h>

int main()
{
int x;

for( x = 0; x < 10; x++ )
{
cout<< x << endl;
}

return 0;
}

Run that, and mess around with the numbers, thats the best way to understand. If you can predict the output from what you set the numbers to, then you have mastered thefor loop :-)

Do/ While Loops:
Sytac:

do
{      1
statements;
}               2

while( condition );

1. The statemnets you want to have looped
2. The Controll of the loop, untill the condition can no longer equal true

Put it all together, An example using the do/while loop:

#include &ltiostream.h>

int main()
{
int x = 0;

do
{
cout<< x << endl;
x++;
}

while( x < 10);

Once again the do/while loop will count from 0 - 9, based on the incremation and the condition.

While Loop:
Sytac:

while( conditions )
{
statements;
}

Now you must be saying whats the difference between the too loops? But their is a simple answer to that which is, in the do/while
loop the condition is checked at the bottom of the statement, and the other is checked at the top. Just depends on what the user
wants the loop to do.....

You Put it an example together im tired of typing....heh.
I think its time you try to make an example from it, as a programer you have to slove problems. You cant be told what to do all the time, try it out and tell me the example :P
writer: brian

Forums: