|
Looping is probably one of the most important programming concepts in existence. There are so many applications of loops it would be impossible to list them all. To name a few though, things like parsing a string, trapping for errors, and animation. Also, since it will allow you to execute a block of code over and over, it saves time and typing. Now, depending on what kind of programming language you came from, loops might already be familiar to you, but if you've come from a low level programming language such as assembly or (god forbit) GWBasic, you are probably more familiar with jump or goto statements. Well, loops take into account all that lovely comparison crap you used to have to do before and puts it into one nice package. The easiest and most used of these loops is the for loop.
Syntax:
for ( variable initialization; condition; variable update ) {
Code to execute while the condition is true
}
Example:
#include
using namespace std;
int main()
{
for ( int x = 0; x < 10; x++ ) {
cout<< x <
}
cin.get();
}
While Loop
The while loop is almost exactly the same as the do loop except that its condition is tested at the start of the loop instead of at the end... and the format is slightly different. The easiest way to see this is simply to re-write the above example with a while loop.
Example:
#include
using namespace std;
int main()
{
int x = 0;
while ( x < 10 ) {
cout<< x <
x++;
}
cin.get();
}
Do While Loop
The do while loop is like the while loop except that the condition is tested at the bottom of the loop.
Syntax:
do {
} while (condition);
Example:
#include
using namespace std;
int main()
{
int x;
x = 0;
do {
cout<<"Hello, world!\n";
} while ( x != 0 );
cin.get();
}
|