7. while and do-while Loops
Problem: Given a 30-feet-long yarn, how many times should it be cut in half in order to become shorter than 1 feet?
You could, of course, try to figure out the answer by using an actual piece of yarn, or even by using a calculator. Let us write a computer program to find out the result, instead.
This problem can be interpreted as
necessitating the repetition of a thread halving act. Until now, we have been
using a for
loop to make repetitions, but this time we are about to learn to
use another kind of loop called a do while loop.
A do
while
loop does the repeating (that
is, it iterates) while a given condition is true. The given condition is
checked at the end of each iteration. However, we are getting too much ahead of
ourselves. First let us introduce a variable named length
:
double length=30;
A do
while
loop will repeat the halving of
the variable length
while the value of the variable is greater than 1:
do { length = length / 2; } while(length > 1);
You may notice that, as opposed to for
loops, do
while
loops end with a semicolon. A do
while
loop will repeat the statements inside the braces while the given condition is true. More precisely, the loop condition is examined (also:
checked or verified) only at the end of each iteration.
The statement length=length/2
can be shortened to length/=2
.
Altogether:
#include <iostream> using namespace std; int main() { double length=30; do { length /= 2; } while(length > 1); cout << "The final length is: " << length << endl; }
The result is:
The final length is: 0.9375
In case we were interested in the length after each halving, we would write this program:
#include <iostream> using namespace std; int main() { double length=30; do { length /= 2; cout << "After halving the length is equal to: " << length << endl; } while(length > 1); cout << "The final length is: " << length << endl; }
The result is:
After halving the length is equal to: 15 After halving the length is equal to: 7.5 After halving the length is equal to: 3.75 After halving the length is equal to: 1.875 After halving the length is equal to: 0.9375 The final length is: 0.9375