4.2 The Do-While Loop
4.2 The Do-While Loop
The
The
What
What
Infinite Loops
An
Boolean Variables
Recall
Ex: Vegas
The
Ex: Factorial
The
N! = N(N-1)(N-2)...(3)(2)(1)
Ex: Factorial
Theres
Ex: Factorial
Small
do while
Sometimes
For
example,
int x;
cout<<Please input a positive number\n;
cin>>x;
// Get numbers from console and square
them
while(x > 0) {
cout<<Your number squared is
<<x*x<<endl;
cout<<Please input a positive
number\n;
cin>>x;
do while
In
Just do it
The
Quite
do while
Now
int x;
cout<<Please input a positive number\n;
cin>>x;
// Get numbers from console and square
them
while(x > 0) {
cout<<Your number squared is
<<x*x<<endl;
cout<<Please input a positive
number\n;
cin>>x;
}
do while
with
int x;
// Get numbers from console and square
them
do {
cout<<Please input a positive
number\n;
cin>>x;
cout<<Your number squared is
<<x*x<<endl;
} while(x > 0);
do while
With
int x;
// Get numbers from console and take square root
do {
cout<<Please input a positive number\n;
cin>>x;
cout<<The square root is
<<sqrt( static_cast<double>(x) )<<endl;
} while(x > 0);
The
while vs do while
// Description of do-while
// Description of do-while
loop
loop
do {
while ( condition) {
// Code to be executed
// Code to be executed
here
}
} while(condition);
do while loops are not as common
and can be more difficult
to read because the condition is at the bottom
Therefore,
How
while vs do while
The Obvious Way
// Code to be executed
// Description of do-while
loop
while (condition) {
// Code to be
executed
}
while vs do while
int x;
bool flag = true;
// Get numbers from console and square
them
while(flag) {
cout<<Please input a positive
number\n;
cin>>x;
cout<<Your number squared is
<<x*x<<endl;
flag = (x > 0);
}