by John
Kopp
Welcome to About.com's C++ tutorial. This lesson covers
three constructs that are used to create loops in C++
programs. Loops can be created to execute a block of code for
a fixed number of times. Alternatively, loops can be created
to repetitively execute a block of code until a boolean
condition changes state. For instance, the loop may continue
until a condition changes from false to true, or from true to
false. In this case, the block of code being executed must
update the condition being tested in order for the loop to
terminate at some point. If the test condition is not modified
somehow within the loop, the loop will never terminate. This
creates a programming bug known as an infinite loop.
While
The while loop is used to execute a block of code
as long as some condition is true. If the condition is false from the start the block of code is not
executed at all. Its syntax is as follows.
while (tested condition is satisfied)
{ block of code }
|
Here is a simple example of the use of while. This program
counts from 1 to 100.
#include <iostream> using namespace
std;
int
main() { int count =
1;
while (count <=
100) { cout
<< count <<
endl; count
+= 1; //Shorthand for count = count +
1 }
return
0; } |
Here is a more realistic use of while. This program
determines the minimum number of bits needed to store a positive integer. The largest unsigned number that can
be stored in N bits is (2N - 1).
#include <iostream> using namespace
std;
int
main() { int bitsRequired
= 1; //the power of 2 int
largest = 1; //largest number that can be
stored int powerOf2 =
2; int
number;
cout <<
"Enter a positive integer:
"; cin >>
number;
while (number
>
largest) { bitsRequired
+= 1; //Shorthand for bitsRequired = bitsRequired +
1 powerOf2
= powerOf2 *
2; largest
= powerOf2 -
1; }
cout
<< "To store " << number << " requires
"; cout << bitsRequired
<< " bits" <<
endl;
return 0; }
|
Next page > Do
and For Loops > Page 1,
2,
3