Chap4_ControlStructures
Chap4_ControlStructures
Chap4_ControlStructures
CONTROL STRUCTURES
◼ 1.Selection criteria
◼ 2.The if-else statement
◼ 3.Nested if statement
◼ 4. Repetition structure
◼ 5. while loops
◼ 6. for loops
◼ 7. Nested loops
◼ 8. do-while Loops
2
1. Selection structure
3
SELECTION CRITERIA
◼ Comparison Operators
Comparison operators are used to compare two operands for
equality or to determine if one numeric value is greater than
another.
Operator Description
---------------------------------------------------
&& AND
|| OR
! NOT
◼ Example:
(age > 40) && (term < 10)
(age > 40) || (term < 10)
!(age > 40)
( i==j) || (a < b) || complete
5
Operator precedence
◼ The relational and logical operators have a hierarchy
of execution similar to the arithmetic operators.
Level Operator Associativity
-------------------------------------------------------
1. ! unary - ++ -- Right to left
2. * / % Left to right
3. + - Left to right
4. < <= > >= Left to right
5. == != Left to right
6. && Left to right
7. || Left to right
8. = += -= *= /= Right to left
6
◼ Example: Assume the following declarations:
7
Order of evaluation
8
The bool Data Type
◼ As specified by the ANSO/ISO standard, C++ has a built-in
Boolean data type, bool, containing the two values true and false.
◼ The actual values represented by the bool values, true and false,
are the integer values 1 and 0, respectively.
◼ Example 4.1.1
#include<iostream>
using namespace std;
int main()
{
bool t1, t2;
t1 = true;
t2 = true;
cout << “The value of t1 is “<< t1
<< “\n and the value of t2 is “<< t2 << endl;
return 0;
}
9
2. THE if-else STATEMENT
Previous
The if-else statement directs statement
the computer to select a
sequence of one or more
statements based on the
No
result of a comparison. Is condition
true ?
The syntax: Yes
if (conditional expression) {
Statement 1 Statement 2
statements;
}
else {
statements;
}
//if only 1 statement, then we can skip the block {} for if-else
10
START
Example 4.2.1
Input We construct a C++ program for
taxable
determining income taxes.
Yes Assume that these taxes are
taxable <= assessed at 2% of taxable
CUTOFF?
incomes less than or equal to
No $20,000. For taxable income
greater than $20,000, taxes are
taxes = HIGHRATE*(taxable –
CUTOFF) + FIXEDAMT 2.5% of the income that
exceeds $20,000 plus a fixed
taxes = LOWRATE*taxable
amount of $400.
Output
taxes
END
11
Example 4.2.1
#include <iostream>
#include <iomanip>
using namespace std;
const float LOWRATE = 0.02; // lower tax rate
const float HIGHRATE = 0.025; // higher tax rate
const float CUTOFF = 20000.0; // cut off for low rate
const float FIXEDAMT = 400;
int main()
{
float taxable, taxes;
cout << "Please type in the taxable income: ";
cin >> taxable;
if (taxable <= CUTOFF)
taxes = LOWRATE * taxable;
else
taxes = HIGHRATE * (taxable - CUTOFF) + FIXEDAMT;
// set output format
cout << setiosflags(ios::fixed)
<< setiosflags(ios::showpoint)
<< setprecision(2);
cout << "Taxes are $ " << taxes << endl;
return 0; 12
}
setiosflags this manipulator is used to control different input
and output settings.
setioflag(ios::fixed) means the output field will use
conventional fixed-point decimal notation. (ex: 12.568)
setiosflag(ios::showpoint) means the output field will show the
decimal point for floating point number.
setiosflag(ios::scientific) means the output field will use
exponential notation. (1.0e-10)
The results of the above program:
Please type in the taxable income: 10000
Taxes are $ 200
and
Please type in the taxable income: 30000
Taxes are $ 650
13
Block Scope
◼ All statements within a compound statement
constitute a single block of code, and any variable
declared within such a block only is valid within the
block.
◼ The location within a program where a variable can
be used formally referred to as the scope of the
variable.
14
◼ Example:
{ // start of outer block
int a = 25;
int b = 17;
cout << “The value of a is “ << a << “ and b is “ << b << endl;
{ // start of inner block
float a = 46.25;
int c = 10;
cout << “ a is now “ << a << “b is now “ << b
<< “ and c is “ << c << endl;
}
cout << “ a is now “ << a
<< “b is now “ << b << endl;
} // end of outer block
The output is
The value of a is 25 and b is 17
a is now 46.25 b is now 17 and c is 10
a is now 25 b is now 17
15
One-way Selection
◼ A useful modification of the
if-else statement involves Previous
statement
omitting the else part of the
statement. In this case, the if
No
statement takes a shortened Is condition
true ?
format:
Yes
Statement(s)
if (conditional expression) {
statements;
}
16
Example 4.2.2
The following program displays an error message for the grades
that is less than 0 or more than 100.
#include <iostream>
using namespace std;
int main()
{
int grade = 0;
cout << "\nPlease enter a grade: ";
cin >> grade;
if(grade < 0 || grade > 100)
cout << " The grade is not valid\n";
return 0;
}
17
3. NESTED if STATEMENT
◼ The inclusion of one or more if statement within an existing if
statement is called a nested if statement.
◼ The if-else Chain
When an if statement is included in the else part of an existing
if statement, we have an if-else chain.
if (expression-1)
statement-1
else if (expression-2)
statement-2
else
statement-3
◼ Example 4.3.1
18
The output of the above
#include <iostream> program:
#include <cmath>
#include <iomanip> Enter the coefficients of the
using namespace std; equation:
int main() 1 5 6
{ x1 = -2.0 x2 = -3.0
double a, b, c, del, x1, x2;
cout << “Enter the coefficients of the equation: “<< endl;
cin >> a >> b >> c;
del = b*b – 4.0*a*c;
if (del == 0.0)
{
x1 = x2 = -b/(2*a);
cout << "x1 = “ << x1 << setw(20) << “x2 = “ << x2 << endl;
}
else if (del > 0.0)
{
x1 = (-b + sqrt(del))/(2*a);
x2 = (-b – sqrt(del))/(2*a);
cout << "x1 = “ << x1 << setw(20) << “x2 = “ << x2 << endl;
}
else // del < 0
cout << "There is no solution\n";
return 0; 19
}
THE switch STATEMENT
◼ The switch statement controls program flow by executing a set
of statements depending on the value of an expression.
Introduction to Computing 20
Execution of the switch statement
◼ The expression in the switch statement must evaluate to
an integer result.
Introduction to Computing 21
break statements in the switch statement
Introduction to Computing 22
#include <iostream.h>
using namespace std;
int main()
{
int iCity;
cout << “Enter a number to find the state where a city is located. \n “;
cout << “1. Boston” << endl;
cout << "2. Chicago" << endl;
cout << "3. Los Angeles” << endl;
cout << "4. Miami” << endl;
cout << "5. Providence” << endl;
cin >> iCity;
switch (iCity)
{
case 1:
cout << "Boston is in Massachusetts " << endl;
break;
case 2:
cout << "Chicago is in Illinois " << endl;
break;
Introduction to Computing 23
case 3:
cout << "Los Angeles is in California " << endl;
break;
case 4:
cout << "Miami is in Florida " << endl;
break;
case 5:
cout << "Providence is in Rhode Island " << endl;
break;
default:
cout << “You didn’t select one of the five cities” << endl;
} // end of switch
return 0;
}
Introduction to Computing 24
The output of the above program:
3
Los Angeles is in California
Introduction to Computing 25
When writing a switch statement, you can use multiple case
values to refer to the same set of statements; the default label
is optional.
switch(number)
{
case 1:
cout << “Have a Good Morning\n”;
break;
case 2:
cout << “Have a Happy Day\n”;
break;
case 3:
case 4:
case 5:
cout << “Have a Nice Evening\n”;
}
Introduction to Computing 26
4. Repetition structures
◼ C++ provides three different forms of repetition structures:
1. while structure
2. for structure
3. do-while structure
◼ If the test is at the end of the loop, the type of loop is a post-
test loop.
27
Fixed count loop and variable condition loop
◼ In addition to where the condition is tested, repeating sections
of code are also classified.
◼ In a fixed count loop, the condition is used to keep track of how
many repetitions have occurred. In this kind of loops, a fixed
number of repetitions are performed, at which point the
repeating section of code is exited.
28
5.while loops
The while statement is used
for repeating a statement or
series of statements as long
as a given conditional Enter the while statement
expression is evaluated to
true.
false
test the
condition ?
The syntax for the while true
statement:
Execute the
statement (s)
29
Example 5.2.1
1 2 3 4 5 6 7 8 9 10
30
In the above program, the loop incurs a counter-controlled
repetition. Counter-controlled repetition requires:
1) the name of a control variable (the variable count )
2) the initial value of the control variable ( count is
initialized to 1 in this case )
3) the condition that tests for the final value of the control
variable (i.e., whether looping should continue) ;
4) the increment (or decrement) by which the control
variable is modified each time through the loop.
31
Sentinels
◼ In programming, data values used to indicate either the
start or end of a data series are called sentinels.
◼ The sentinels must be selected so as not to conflict with
legitimate data values.
Example 5.3.2
#include <iostream>
using namespace std;
const int HIGHGRADE = 100; // sentinel value
int main()
{
float grade, total;
grade = 0;
total = 0;
cout << "\nTo stop entering grades, type in any number"
<< " greater than 100.\n\n";
32
cout << "Enter a grade: ";
cin >> grade;
while (grade <= HIGHGRADE)
{
total = total + grade;
cout << "Enter a grade: ";
cin >> grade;
}
cout << "\nThe total of the grades is " << total << endl;
return 0;
}
◼ In the above program, the sentinel is the value 100 for the entered
grade.
33
break statement
◼ The break statement causes an exit from the innermost
enclosing loop.
Example:
while (count <= 10)
{
cout << “Enter a number: “; cin >> num;
if (num > 76) {
cout << “you lose!\n”;
break;
}
else
cout << “Keep on trucking!\n”;
count++;
}
//break jumps to here
34
continue Statements
◼ The continue statement halts a looping statement and restarts
the loop with a new iteration.
int count = 0;
while (count < 30) {
cout << “Enter a grade: “;
cin >> grade;
if (grade < 0 || grade > 100)
continue;
total = total + grade;
count++;
}
35
The null statement
◼ All statements must be terminated by a semicolon. A semicolon with
nothing preceding it is also a valid statement, called the null
statement. Thus, the statement
;
is a null statement.
Example:
if (a > 0)
b = 7;
else ;
goto statement
A goto statement is a kind of jump statement. Its destination is specified
by a label within the statement. A label is simply an identifier followed by
a statement, separated by a colon.
Example:
if (a > 20)
goto esc;
else cout << a*a;
esc: cout << endl;
36
6. for LOOPS
◼ The for statement is used for repeating a statement or series of
statements as long as a given conditional expression evaluates
to true.
37
Enter the for statement
Initialization expression
false
test the
condition ?
true
Execute the
statement (s)
38
Example 4.6.1
// This program prints the even number from 2 to 20
#include <iostream>
using namespace std;
int main() {
int count;
for (count = 2; count <= 20; count = count + 2)
cout << count << " ";
return 0;
}
2 4 6 8 12 14 16 18 20
39
Example 4.6.2 In this example, we solve this problem:
A person invests $1000.00 in a saving account with 5 percent
interest. Assuming that all interest is left on deposit in the account,
calculate and print the amount of money in the account at the end of
each year for 10 years. Use the following formula for determining
these amounts:
a = p(1 + r)n
where p is the original amount invested, r is the annual interest rate
and n is the number of years and a is the amount on deposit at the
end of the nth year.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
double amount = 0, principal = 1000.0, rate = 0.05;
cout << "Year” << setw(21) << "Amount on deposit" << endl;
40
cout << setiosflags(ios::fixed | ios::showpoint) <<
setprecision(2);
for (int year = 1; year <= 10; year++) {
amount = principal*pow(1.0 + rate, year);
cout << setw(4) << year << setw(21) << amount << endl;
}
return 0;
} The output of the above program:
41
7. NESTED LOOPS
In many situations, it is convenient to use a loop contained
within another loop. Such loops are called nested loops.
◼ Example 4.7.1
#include <iostream>
using namespace std;
int main()
{
const int MAXI = 5; The output of the
program:
const int MAXJ = 4;
int i, j; i is now 1
for(i = 1; i <= MAXI; i++) // start of outer loop j=1 j=2 j=3 j=4
{ i is now 2
j=1 j=2 j=3 j=4
cout << "\n i is now " << i << endl; i is now 3
for(j = 1; j <= MAXJ; j++) // start of inner loop j=1 j=2 j=3 j=4
cout << " j = " << j; // end of inner loop i is now 4
} // end of outer loop j=1 j=2 j=3 j=4
i is now 5
cout << endl; j=1 j=2 j=3 j=4
return 0;
} 42
8. do-while LOOPS Enter the do-while
statement
Execute the
statement (s)
false
test the
condition ?
true
do {
statements;
} while (conditional expression);
43
Example of do-while
◼ Example 4.8.1 A program to find the sum of even numbers:
2+4+…+n
#include<iostream>
using namespace std;
void main() {
int max, sum = 0, digit;
digit = 2;
cout << “ enter a number \n”;
cin >> max; Output of the program:
do { Enter a number
sum = sum + digit; 10
2+4+…+10 sum = 30
digit = digit + 2;
} while (digit <= max);
cout << “ 2 + 4 +…+ “<< max << “ sum = ‘’;
cout << sum << endl;
}
44
Exercise
◼ Write a C++ program:
❑ to check whether a number is positive, negative or
zero
❑ to find the largest among 3 different numbers
❑ to solve the linear equation ax + b = 0
❑ to find number of days in a month and year
◼ Ex: 10 2023 → 31
Programming Fundamentals 45
Exercise
Programming Fundamentals 46