if ( condition )
statement;
condition
evaluated
true
false
statement
The if Statement
An example of an if statement:
if (sum > MAX)
delta = sum - MAX;
cout<<The sum is << sum;
if ( a == 10 || b < 20 )
The if Statement
What do the following statements do?
if (top >= MAXIMUM)
top = 0;
Sets top to zero if the current value of top is greater
than or equal to the value of MAXIMUM
condition
evaluated
true false
statement1 statement2
Block Statements
Several statements can be grouped together
into a block statement delimited by braces
condition
evaluated
true false
statement
The while Statement
An example of a while statement:
int count = 1;
while (count <= 5)
{
cout<<count;
count++;
}
statement
true
condition
evaluated
false
The do while Statement
An example of a do loop:
int count = 0;
do
{
count++;
cout<<count;
} while (count < 5);
statement
condition
evaluated
true
condition
true false
evaluated
statement
false
The for Statement
A for statement has the following syntax:
The initialization The statement is
is executed once executed until the
before the loop begins condition becomes false
condition
evaluated
true false
statement
increment
The for Statement
A for loop is functionally equivalent to the
following while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
The for Statement
An example of a for loop:
for (int count=1; count <= 5; count++)
cout<<count;
for(i=1; ;i=i+1)
{
#include <iostream>
using namespace std;
int main() {
int number; char character;
for (number = 32 ; number <= 126 ; number = number + 1)
{
character = number;
cout << "The character '" << character;
cout << "' is represented as the number ";
cout << number << " in the computer.\n";
} return 0;
}
#include <iostream>
using namespace std;
int main()
{ int number; char character;
number = 32;
while (number <= 126)
{
character = number;
cout << "The character '" << character; cout << "' is
represented as the number ";
cout << number << " in the computer.\n"; number++; }
return 0;
}
do
{ cout << "Enter the candidate's score: ";
cin >> candidate_score;
if (candidate_score > 100 || candidate_score < 0)
cout << "Score must be between 0 and 100.\n";
}
while (candidate_score > 100 || candidate_score < 0);
cout << "Enter the candidate's score: ";
cin >> candidate_score;
while (candidate_score > 100 || candidate_score < 0)
{
cout << "Score must be between 0 and 100.\n";
cout << "Enter the candidate's score: ";
cin >> candidate_score;
}
C provides two commands to control how we
loop:
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.
The break and continue Statements
The break statement causes an exit from the
innermost enclosing loop or switch statement.
The continue statement causes the current iteration
of a loop to stop and the next iteration to begin
immediately.
Example Using a break Statement
while (1) {
cin>>x;
if (x < 0.0)
break;
cout<<sqrt(x);
}