0% found this document useful (0 votes)
19 views

Control Structures

The document discusses control structures in C++ including selection structures like if-else statements and switch statements as well as repetition structures like while, for, and do-while loops. It provides examples of using if-else statements to determine income taxes based on taxable income and check if a grade is valid. Nested if statements and if-else chains are also introduced.

Uploaded by

nguyenhoai040705
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Control Structures

The document discusses control structures in C++ including selection structures like if-else statements and switch statements as well as repetition structures like while, for, and do-while loops. It provides examples of using if-else statements to determine income taxes based on taxable income and check if a grade is valid. Nested if statements and if-else chains are also introduced.

Uploaded by

nguyenhoai040705
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Chapter 4

CONTROL STRUCTURES

Introduction to computer science


1
Outline

n 1.Selection structure
q The if-else statement
q switch statement
n 2. Repetition structure
q while loops
q for loops
q do-while Loops

2
1. Selection structure

n The flow of control means the order in which a program’s


statements are executed.
n Unless directed otherwise, the normal flow of control for
all programs is sequential.

n Selection, repetition and function invocation structures


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

n In this chapter, you learn to use selection structures and


repetition structures in C++

3
SELECTION CRITERIA
n 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
n 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
n Example:
(age > 40) && (term < 10)
(age > 40) || (term < 10)
!(age > 40)
( i==j) || (a < b) || complete

5
Operator precedence and associativity
n 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
n 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
n As specified by the ANSI/ISO standard, C++ has a built-in Boolean
data type, bool, containing the two values true and false.
n The actual values represented by the bool values, true and false, are
the integer values 1 and 0, respectively.
n 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
THE if-else STATEMENT
Previous
The if-else statement directs statement
the computer to select a
statement based on the result
of an expression.
No
Is condition
The syntax: true ?

if (conditional expression) Yes

statement 1
Statement 1 Statement 2
else
statement 2

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 << fixed
<< showpoint // show the decimal point
<< setprecision(2);
cout << "Taxes are $ " << taxes << endl;
return 0; 12
}
The results of the above program:
Please type in the taxable income: 10000
Taxes are $ 200.00
and
Please type in the taxable income: 30000
Taxes are $ 650.00

13
Block Statement
n Syntax: { declarations or statements }
n A block statement is used to combine many statements
into one statement.
n Declarations are allowed in a block statement. These
declarations are valid only within the block and hide
other outside declarations with the same name
n The location within a program where a variable can be
used formally referred to as the scope of the variable.

14
n 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
n 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
format: true ?

Yes

Statement(s)
if (conditional expression)
statement

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
NESTED if STATEMENT
n The inclusion of one or more if statement within an existing if
statement is called a nested if statement.
n 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
n 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
}
switch statement
t=expression

Y
n A convenient way to write multi-way t==v1
statement
n Syntax: N Statements 1
switch (expression) { Y
t==v2
case v1: statements 1
case v2: statements 2 N Statements 2
case v3: statements 3
… Y
t==v3
default: statements 4
} N Statements 3
n break; statement in a switch statement
transfers control out of the switch
statement Statements 4

Programming Fundamentals 20
Example
#include <iostream>
using namespace std;
int main() {
char o;
float num1, num2;
cout << "Enter an operator (+, -, *, /): ";
cin >> o;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch (o) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;
break;
default:
cout << "Error! operator is not correct”;
}
return 0;
}

Programming Fundamentals 21
2. Repetition structures
n C++ provides three different forms of repetition structures:
1. while structure
2. for structure
3. do-while structure

n Each of these structures requires a condition that must be


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

n If the test is at the beginning of the loop, the type of loop is a pre-test
loop.

n If the test is at the end of the loop, the type of loop is a post-test
loop.

22
Fixed count loop and variable condition loop
n In addition to where the condition is tested, repeating sections of
code are also classified.
n 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.

n In many situations, the exact number of repetitions are not known in


advance. In such cases, a variable condition loop is used.
n 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.

23
while loops
The while statement is used for
repeating a statement as long
as a given conditional
expression is evaluated to true. Enter the while statement

The syntax for the while false


statement: test the
condition ?

true

while (condition expression) Execute the


statement (s)
statement
Exit the while
statement

24
Example 5.2.1
// This program prints out the total of a sequence of grades until
an invalid grade is input
#include <iostream>
using namespace std;
const int HIGHGRADE = 100;
const int LOWGRADE = 0;
int main() {
int grade,sum = 0;
cout << “Input a grade between 0 and 100: “;
cin >> grade; /
while (grade >= LOWGRADE && grade <= HIGHGRADE) {
sum += grade;
cout << “Input a grade between 0 and 100: “;
cin >> grade;
}
cout << “The total of valid grades: “ << sum << endl;
return 0;
}
25
Sentinels
n In programming, data values used to indicate either the start
or end of a data series are called sentinels.
n The sentinels must be selected so as not to conflict with
legitimate data values.

26
do-while statement Enter the do-while
statement

Execute the
statement (s)

false
test the
condition ?

true

n do..while statement is used


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

do
statement
while (conditional expression);

27
Example of do-while
n Example 4.8.1This program prints out the total of a sequence of
grades until an invalid grade is input
#include <iostream>
using namespace std;
int main()
{
int grade = 0,sum = 0;
do {
sum += grade;
cout << "Input a grade between 0 and 100: ";
cin >> grade;
}
while (grade >= 0 && grade <= 100) ;
cout << "The total of valid grades: " << sum << endl;
return 0;
}
28
Example of do-while
n Example 4.8.1This program prints out from 1 to 10
#include <iostream>
using namespace std;
int main()
{
int count;
count = 1;
while (count <=10) {
cout << count << “ “;
count++;
}
return 0;
}

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

30
for statement
n The for statement is used for repeating a statement or series of
statements as long as a given conditional expression evaluates
to true.

n 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

n The syntax of the for statement:

for (initialization expression; condition; update statement)


statement

31
Enter the for statement

Initialization expression

false
test the
condition ?

true

Execute the
statement (s)

Exit the for


statement
Execute the update
statement

32
Example 4.6.1
//#include <iostream>
using namespace std;
int main() {
int count;
for (count = 1; count <= 10; count++)
cout << count << " ";
return 0;
}

The output of the above program:

1 2 3 4 5 6 7 8 9 10

33
break statement in loop
n 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 statement
n 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++;
}

n In the above program, invalid grades are simply ignored and only
valid grades are added to the total.

35
The null statement
n 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
NESTED LOOPS
In many situations, it is convenient to use a loop contained
within another loop. Such loops are called nested loops.
n 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;
} 39

You might also like