Chap4_ControlStructures

Download as pdf or txt
Download as pdf or txt
You are on page 1of 46

Chapter 4

CONTROL STRUCTURES

Introduction to computer science


1
Outline

◼ 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

◼ The flow of control means the order in which a


program’s statements are executed.
◼ Unless directed otherwise, the normal flow of control
for all programs is sequential.

◼ Selection, repetition and function invocation


structures permit the flow of control to be altered in
a defined way.

◼ In this chapter, you learn to use selection structures


and repetition structures in C++

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.

A Boolean value of true or false is returned after two operands


are compared. C++ uses a nonzero value to represent a true
and a zero value to represent a false value.

Operator Description Examples


---------------------------------------------------------------------------------------
== equal a ==‘y’
!= not equal m!= 5
> greater than a*b > 7
< less than b<6
<= less than or equal b <= a
>= greater than or equal c >= 6
4
Logical operators
◼ Logical operators are used for creating more complex
conditions. Like comparison operators, a Boolean value of true
or false is returned after the logical operation is executed.

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:

char key = ‘m’;


int i = 5, j = 7, k = 12;
double x = 22.5;

Expression Equivalent Value Interpretation


--------------------------------------------------------------------------------------------
i + 2 = = k-1 (i + 2) = = ( k –1) 0 false
‘a’ +1 = = ‘b’ (‘a’ +1) = = ‘b’ 1 true
25 >= x + 1.0 25 >= (x + 1.0) 1 true
key –1 > 20 (key –1) > 20 0 false

7
Order of evaluation

The following compound condition is evaluated as:

(6*3 = = 36/2) || (13<3*3 + 4) && !(6-2 < 5)


(18 = = 18) || (13 < 9 + 4) && !(4 < 5)
1 || (13 < 13) && ! 1
1 || 0 && 0
1 || 0
1

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

// This program can solve quadratic equation

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.

◼ The syntax for the switch statement:


switch(expression){
case label1:
statement(s) 1; Note: The value of
break; expression must be an
case label2; integer data type, which
statement(s) 2; includes the char, int,
long int, and short data
break;
types.
default:
statement(s) 3;
}

Introduction to Computing 20
Execution of the switch statement
◼ The expression in the switch statement must evaluate to
an integer result.

◼ The switch expression’s value is compared to each of


these case values in the order in which these values are
listed until a match is found. When a match occurs,
execution begins with the statement following the match.

◼ If the value of the expression does not match any of the


case values, no statement is executed unless the
keyword default is encountered. If the value of the
expression does not match any of the case values,
program execution begins with the statement following
the word default.

Introduction to Computing 21
break statements in the switch statement

◼ The break statement is used to identify the end of a


particular case and causes an immediate exit from
the switch statement.

◼ If the break statements are omitted, all cases


following the matching case value, including the
default case, are executed.

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:

Enter a number to find the state where a city is located.


1. Boston
2. Chicago
3. Los Angeles
4. Miami
5. Providence

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

◼ Each of these structures requires a condition that must be


evaluated.
◼ The condition can be tested at either (1) the beginning or (2) the
end of the repeating section of code.

◼ If the test is at the beginning of the loop, the type of loop is a


pre-test loop.

◼ 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.

◼ In many situations, the exact number of repetitions are not


known in advance. In such cases, a variable condition loop is
used.
◼ In a variable condition loop, the tested condition does not
depend on a count being achieved, but rather on a variable that
can change interactively with each pass through the loop.
When a specified value is encountered, regardless of how
many iterations have occurred, repetitions stop.

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)

while (condition expression) { Exit the while


statement
statements;
}

29
Example 5.2.1

// This program prints out the numbers from 1 to 10


#include <iostream>
using namespace std;
int main()
{
int count;
count = 1; // initialize count
while (count <= 10) {
cout << count << " ";
count++; // increment count
}
return 0;
}
The output of the above program:

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++;
}

◼ In the above program, invalid grades are simply ignored and


only valid grades are added to the total.

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.

◼ One of the main differences between while statement and for


statement is that in addition to a condition, you can also
include code in the for statement
- to initialize a counter variable and
- changes its value with each iteration

◼ The syntax of the for statement:

for (initialization expression; condition; update statement) {


statement(s);
}

37
Enter the for statement

Initialization expression

false
test the
condition ?

true

Execute the
statement (s)

Exit the for


statement
Execute the update
statement

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;
}

The output of the above program:

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:

Year Amount on deposit


1 1050.00
2 1102.50
3 1157.62
4 1215.51
5 1276.28
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89

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..while statement is used


to create post-test loops.
Exit the do-while
◼ The syntax: statement

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

◼ Write a C++ program:


❑ to calculate sum/product of all odd/even positive
integers less than N
❑ to check whether a number is prime or not
❑ to find highest common factor of two numbers
❑ to count and list all factors of a given number
❑ to calculate
◼ n! (n > 0)
◼ P(n)=1.3.5...(2n+1) (n > 0)
◼ S(n)= 1+3+5+n...+(2n+1) (n > 0)

Programming Fundamentals 46

You might also like