Programming with C/C++ Language
Introduction to the C++ Language
Loops
Loops
Loops are used to repeat a block of code. There are three types of loops:
for, while, and do..while. Each of them has their specific
uses.
1. FOR loop
FOR loops are the most useful type.
The syntax for a for loop is:
for ( variable initialization; condition; variable update ) {
Code to execute while the condition is true
}
The variable initialization allows us to either declare a variable and give it
a value or give a value to an already existing variable.
Second, the condition tells the program that while the conditional
expression is true the loop should continue to repeat itself.
The variable update section is the increment of the variable.
It is possible to do things like x++, x = x + 10, or even x = random (5),
or other functions that do nothing to the variable.
Notice that a semicolon separates each of these sections,
that is important.
Example:
#include
using namespace std;
int main()
{
// The loop goes while x < 5, and x increases by one every loop
for ( int x = 0; x < 5; x++ ) { // The loop goes while x < 5,
// and x increases by one every loop
// The loop condition checks the conditional statement
// before it loops again.
// consequently, when x equals 5 the loop breaks.
// x is updated before the condition is checked.
cout<< x <<endl;
}
cin.get();
}
This is an example of a for loop: x is set to zero,
while x is less than 5 it calls cout<< x <<endl; and it adds 1
to x until the condition is met.
2. WHILE loop
The basic structure of while
loops is:
while ( condition ) {
Code to execute while the condition is true
}
Notice that a while loop is the same as a for loop without the
initialization and update sections. However, an empty condition is not
legal for a while loop as it is with a for loop.
Example:
#include <iostream>
using namespace std;
int main()
{
int x = 0;
while ( x < 5 ) { // While x is less than 10
cout<< x <<endl;
x++; // Update x so the condition can be met eventually
}
cin.get();
}
3. DO..WHILE loop
A do..while loop is a reversed while loop. The structure of DO..WHILE loops is
do {
} while ( condition );
Notice that the condition is tested at the end of the block instead
of the beginning, so the block will be executed at least once.
Example:
#include
using namespace std;
int main()
{
int x;
x = 1;
do {
// "Hello, world!" is printed at least one time
// even though the condition is false
cout<<"Hello, world!\n";
} while ( x != 1 );
cin.get();
}
Not that we must include a trailing semi-colon after the while in the
above example. Notice that this loop will execute once, because it automatically
executes before checking the condition.
|