|
|
C++ Language Tutorial Page 5
While and For Loops
Ned Bingham
Previous Index Next
While Loops
     While loops are very similar to if statements if every way.
In fact, their syntax is exactly the same, and they do almost exactly the same
thing, except that while loops repeat the segment of code within the brackets while
the boolean expression remains true. Here is the syntax.
while (boolean expression)
{
code goes here
}
Here is an example that prints x as it counts to 10:
#include <iostream.h>
int main()
{
int x = 0;
while (x < 10)
{
cout << "x = " << x << endl;
x++;
}
return 0;
}
For Loops
     For loops are very similar to while loops, only they have an
integrated counter. That while loop that counts to ten can easily be converted to
a for loop. Here is the syntax.
for (counter declaration; boolean expression; counter increment expression)
{
code goes here...
}
Here is that same example with a for loop instead:
#include <iostream.h>
int main()
{
for (int x = 0; x < 10; x++)
{
cout << "x = " << x << endl;
}
return 0;
}
|
|