Chapter 4control Structures

You might also like

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

Control structures

Chapter 4

Introduction to computing
Outline
1. Control structures
2. Selection structures
2.1. Selection criteria
2.2 The if-else statement
2.3 Nested if statement
2.4 The Switch statement
3. Repetition structures
3.1 while loops
3.2 for loops
3.3 Nested loops
3.4 do-while Loops

Introduction to Computing 2
Outline
1. Control structures
2. Selection structure
2.1. Selection criteria
2.2 The if-else statement
2.3 Nested if statement
2.4 The Switch statement
3. Repetition structure
3.1 while loops
3.2 for loops
3.3 Nested loops
3.4 do-while Loops

Introduction to Computing 3
Control structures
• The flow of control means the order in which a program’s
statements are executed.
• Programs are written using three basic structures
−Sequence: a sequence is a series of statements that execute one after
another
−Selection (branching): selection (branch) is used to execute different
statements depending on certain conditions
−Repetition (loop or iteration): repetition (looping) is used to repeat
statements while certain conditions are met.
• Called control structures or logic structures
Introduction to Computing 4
Sequence structure
• The sequence structure directs the
computer to process the program Action 1

instructions, one after another, in


the order listed in the program
Action 2

Action 3

Introduction to Computing 5
Selection structure (Branch)
• Selection structure makes
False True
a decision and then takes Condition
an appropriate action
based on that decision
• Also called the decision
Action A Action B
structure

Introduction to Computing 6
Repetition structure (Loop)
• Repetition structure: directs
False
computer to repeat one or Condition
more instructions until
some condition is met. True
• Also called a loop or
iteration
Action B

While-Do control structure

Introduction to Computing 7
Outline
1. Control structures
2. Selection structure
2.1. Selection criteria
2.2 The if-else statement
2.3 Nested if statement
3. Repetition structure
3.1 while loops
3.2 for loops
3.3 Nested loops
3.4 do-while Loops

Introduction to Computing 8
Selection criteria
• Comparison operators are used to compare two operands.
• 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

Introduction to Computing 9
Selection criteria
• Logical operators are used for creating more complex conditions.
• A Boolean value of true or false is returned after the logical operation is
executed.
Operator Description A && B (B) True (B) False
(A) True T F
&& AND (A) False F F
|| OR
! NOT A || B (B) True (B) False
(A) True T T
Example: (age > 40) && (term < 10)
(A) False T F
(age > 40) || (term < 10)
!(age > 40) !A
( i==j) || (a < b) || complete (A) True F
(A) False T
Introduction to Computing 10
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

Introduction to Computing 11
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

Introduction to Computing 12
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 (true)

Introduction to Computing 13
The bool Data Type
#include<iostream>
• Boolean data type, bool,
using namespace std;
containing the two values
int main()
true and false. {
• The actual values bool t1, t2;
represented by the bool t1 = true;
t2 = false;
values, true and false, are the
cout << “The value of t1 is “ << t1
integer values 1 and 0 ,
<< “\n and the value of t2 is “<< t2 <<
respectively. endl;
return 0;
}
Introduction to Computing 14
The if-else statement
• The if-else statement directs the computer
to select a sequence of one or more
statements based on the result of a False True
comparison. Condition

• The syntax:
if (conditional expression) {
statements; //true
Statements A Statements B
}
else {
statements; // false
}
//if only 1 statement, then we can skip the block {} for if-else
Introduction to Computing 15
Example: STA RT

• Construct a C++ program for In p u t


ta x a b le

determining income taxes.


Y es
• Assume that these taxes are ta x a b le < =
C U TO FF?
assessed at 2% of taxable
incomes less than or equal to No

$20,000. For taxable income ta x e s = H IG H R A T E * (ta x a b le –


C U T O F F ) + F IX E D A M T

greater than $20,000, taxes are ta x e s = L O W R A T E * ta x a b le

2.5% of the income that


exceeds $20,000 plus a fixed
O u tp u t
amount of $400. ta x e s

END
Introduction to Computing 16
#include <iostream>
Example #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;
cout << setiosflags(ios::fixed) << setiosflags(ios::showpoint)
<< setprecision(2); // set output format
cout << "Taxes are $ " << taxes << endl;
Introduction to Computing 17
return 0; }
• Setiosflags: 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. (ex: 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

Introduction to Computing 18
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.

Introduction to Computing 19


Example The output is
The value of a is 25 and b is 17
{ // start of outer block a is now 46.25, b is now 17 and c is 10
int a = 25; a is now 25, b is now 17
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
Introduction to Computing 20
One-way Selection
Previous
• A useful modification of the if- statement
else statement involves omitting
the else part of the statement. In No
Is condition
this case, the if statement takes true ?

a shortened format: Yes

Statement(s)
if (conditional expression) {
statements;
}

Introduction to Computing 21
Example
• 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 << "Please enter a grade: ";
cin >> grade;
if (grade < 0 || grade > 100)
cout << "\nThe grade is not valid";
return 0;
} Introduction to Computing 22
Nested if statements
• The inclusion of one or more if statement within an existing if statement is
called a nested if statement.
• The if-else Chain: an if statement is included in the else part of an existing if
statement
if (expression-1)
statement-1
else if (expression-2)
statement-2
else
statement-3
• Example 4.3.1
• // This program can solve quadratic equation

Introduction to Computing 23


#include <iostream> << “x2 = “ << x2 << endl;
#include <cmath> }
#include <iomanip> else if (del > 0.0)
using namespace std; {
int main() { x1 = (-b + sqrt(del))/(2*a);
double a, b, c, del, x1, x2; x2 = (-b – sqrt(del))/(2*a);
cout << “Enter the coefficients of the cout << "x1 = “ << x1 << setw(20)
equation: “<< endl; << “x2 = “ << x2 << endl;
cin >> a >> b >> c; }
del = b*b – 4.0*a*c; else // del < 0
if (del == 0.0) cout << "There is no solution\n";
{ return 0; }
x1 = x2 = -b/(2*a);
The output of the above program:
cout << "x1 = “ << x1 << setw(20) Enter the coefficients of the equation:
1 5 6
x1 = -2.0
Introduction to Computing x2 = -3.0
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 label: Note: The value of
statement(s); expression must be an
break; integer data type, which
case label: includes the char, int,
statement(s); long int, and short data
break; types.
default:
statement(s);
}

Introduction to Computing 25
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. In this case, the program execution begins with
the statement following the word default.

Introduction to Computing 26
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 27
#include <iostream> break;
using namespace std; case 3:
int main() { cout << "Los Angeles is in California "
int iCity; << endl;
cout << "Enter a number to find the state break;
where a city is located. “ << endl; case 4:
cout << “1. Boston” << endl; cout << "Miami is in Florida " << endl;
cout << "2. Chicago" << endl; break;
cout << "3. Los Angeles” << endl; case 5:
cout << "4. Miami” << endl; cout << "Providence is in Rhode Island "
cout << "5. Providence” << endl; << endl;
cin >> iCity; break;
switch (iCity) { default:
case 1: cout << “You didn‟t select one of the five
cout << "Boston is in Massachusetts " cities” << endl;
<<endl; } // end of switch
break; return 0;
case 2: }
cout << "Chicago is in Illinois " << endl;
Introduction to Computing
#include <iostream> break;
using
Thenamespace
output of the std;above program: case 3:
intEnter
main()a{number to find the state cout << "Los Angeles is in California "
int iCity;a city is located.
where << endl;
cout
1. << "Enter a number to find the state
Boston break;
where
2. a city is located. “ << endl;
Chicago case 4:
cout
3. Los<<Angeles
“1. Boston” << endl; cout << "Miami is in Florida " << endl;
cout
4. << "2. Chicago" << endl;
Miami break;
cout
5. << "3. Los Angeles” << endl;
Providence case 5:
cout << "4. Miami” << endl; cout << "Providence is in Rhode Island "
3cout << "5. Providence” << endl; << endl;
cin >>
Los iCity; is in California
Angeles break;
switch (iCity) { default:
case 1: cout << “You didn‟t select one of the five
cout << "Boston is in Massachusetts " cities” << endl;
<<endl; } // end of switch
break; return 0;
case 2: }
cout << "Chicago is in Illinois " << endl;
Introduction to Computing
Outline
1. Control structures
2. Selection structures
2.1. Selection criteria
2.2 The if-else statement
2.3 Nested if statement
2.4 The Switch statement
3. Repetition structures
3.1 while loops
3.2 for loops
3.3 Nested loops
3.4 do-while Loops

Introduction to Computing 30
Repetition structures
• C++ provides three different forms of repetition structures:
−while structure
−for structure
−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.
Introduction to Computing
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.

Introduction to Computing
while loops Enter the while statement

• The while statement is used for


repeating a statement or series of
statements as long as a given false
test the
conditional expression is condition ?

evaluated to true. true

• The syntax for the while statement: Execute the


statement (s)

Exit the while


while (condition expression) { statement
statements;
}
Introduction to Computing 33
Example
// 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) {
The output of the above program:
cout << count << " ";
count++; // increment count 1 2 3 4 5 6 7 8 9 10
}
return 0;
}

Introduction to Computing 34


Example - Explanation
• 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.

Introduction to Computing 35


Sentinels
• Sentinels: data values used to indicate either the start or end of
a data series
• Sentinels must be selected so as not to conflict with legitimate
data values.

Introduction to Computing 36


Example
#include <iostream> {
using namespace std; total = total + grade;
const int HIGHGRADE = 100; // sentinel cout << "Enter a grade: ";
value cin >> grade;
int main() }
{ cout << "\nThe total of the grades is " <<
float grade, total; total << endl;
grade = 0; return 0;
total = 0; }
cout << "\nTo stop entering grades, type
in any number" In the above program, the sentinel is the
<< " greater than 100.\n\n"; value 100 for the entered grade.
cout << "Enter a grade: ";
cin >> grade;
while (grade <= HIGHGRADE)
Introduction to Computing 37
break statement
while (count <= 10)
• The break {
statement causes cout << “Enter a number: “;
an exit from the cin >> num;
if (num > 76) {
innermost cout << “you lose!\n”;
enclosing loop. break;
}
else
cout << “Keep on trucking!\n”;
count++;
}
//break jumps to here

Introduction to Computing 38
continue Statements
• The continue statement int count = 0;
halts a looping statement int total, grade;
and restarts the loop with total = 0;
a new iteration. while (count < 30) {
cout << “Enter a grade: “;
• In the program, invalid
cin >> grade;
grades are simply ignored if (grade < 0 || grade > 100)
and only valid grades are continue;
added to the total. total = total + grade;
count++;
}

Introduction to Computing 39
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
;

Introduction to Computing
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;
Introduction to Computing
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);
}
Introduction to Computing
Enter the for statement

Initialization expression

false
test the
condition ?

true

Execute the
statement (s)

Exit the for


statement
Execute the update
statement

Introduction to Computing 43
Example
// 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 << " ";
The output of the above program:
return 0;
2 4 6 8 12 14 16 18 20
}
Introduction to Computing
Example
• 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.

Introduction to Computing
#include <iostream>
The output of the program:
#include <iomanip>
#include <cmath> Year Amount on deposit
1 1050.00
using namespace std;
2 1102.50
int main() { 3 1157.62
double amount = 0, principal = 1000.0, rate = 0.05; 4 1215.51
5 1276.28
cout << "Year” << setw(21) << "Amount on deposit" <<
6 1340.10
endl;
7 1407.10
cout << setiosflags(ios::fixed | ios::showpoint) << 8 1477.46
setprecision(2); 9 1551.33
for (int year = 1; year <= 10; year++) { 10 1628.89
amount = principal*pow(1.0 + rate, year);
cout << setw(4) << year << setw(21) << amount << endl;
}
return 0;
}
Introduction to Computing 46
Nested loops #include <iostream>
using namespace std;
• In many situations,
int main()
it is convenient to {
use a loop const int MAXI = 5;
const int MAXJ = 4;
contained within int i, j;
another loop. for (i = 1; i <= MAXI; i++) // start of outer loop
{
• Such loops are cout << "\n i is now " << i << endl;
called nested for (j = 1; j <= MAXJ; j++) // start of inner loop
loops. cout << " j = " << j; // end of inner loop
} // end of outer loop
cout << endl;
return 0;
}
Introduction to Computing 47
Nested loops #include <iostream>
using namespace std;
int main()
{
The output of the program: const int MAXI = 5;
i is now 1 const int MAXJ = 4;
j=1 j=2 j=3 j=4 int i, j;
i is now 2 for (i = 1; i <= MAXI; i++) // start of outer loop
j=1 j=2 j=3 j=4 {
i is now 3
cout << "\n i is now " << i << endl;
j=1 j=2 j=3 j=4
i is now 4 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 5 } // end of outer loop
j=1 j=2 j=3 j=4 cout << endl;
return 0;
}
Introduction to Computing 48
do-while loops
Enter the do-while
• do … while statement is used statement

to create post-test loops.


Execute the
• The syntax: statement (s)

do {
statements; false
test the
condition ?
} true

while (conditional expression);

Exit the do-while


statement

Introduction to Computing 49
Example: A program to find the sum of even numbers: 2+4+…+n
#include<iostream>
using namespace std;
void main() {
int max, sum = 0, digit;
Output of the program:
digit = 2;
Enter a number
cout << “Enter a number \n”;
10
cin >> max;
2+4+…+10 sum = 30
do {
sum = sum + digit;
digit = digit + 2;
} while (digit <= max);
cout << “ 2 + 4 +…+ “<< max << “ sum = ‘’;
cout << sum << endl;
}
Introduction to Computing
EXERCISES
Exercise 1
• Write a program that:
−Gets a character from user
−Checks if it is an Uppercase Alphabet or a Lowercase Alphabet.
−Shows the result
 It is an Uppercase Alphabet 65 - 90
 It is a Lowercase Alphabet 97 - 122
 It is not an Alphabet
ASCII value of character
char ch;
int ascii;
ascii = ch;
Introduction to Computing 52
#include<iostream>
using namespace std;
int main() {
char ch;
int ascii;
cout << "Enter a Character: ";
cin >> ch;
ascii = ch;
cout << endl;
if (ascii>=65 && ascii<=90)
cout << "It is an Uppercase Alphabet";
else if(ascii>=97 && ascii<=122)
cout << "It is a Lowercase Alphabet";
else
cout << "It is not an Alphabet";
cout << endl;
return 0;
} Introduction to Computing 53
Exercise 2
• Write a program that:
−Gets a temperature to be converted
−Gets the type of temperature: f (Fahrenheit) or c (Celsius)
−Converts the temperature to the other type (Fahrenheit to Celsius or
Celsius to Fahrenheit)

Introduction to Computing 54
Exercise
• A student's letter grade is calculated according to the following rules:
Numerical grade Letter grade
------------------------------------------------------------------------------------
Greater than or equal to 90 A
Less than 90 but greater than or equal to 80 B
Less than 80 but greater than or equal to 70 C
Less than 70 but greater than or equal to 60 D
Less than 60 F

• Using this information, write a C++ program that accepts a student’s


numerical grade, converts it to an equivalent letter grade, and
displays the letter grade

Introduction to Computing 55
Exercise
• An angle is considered acute if it is less than 90 degrees, obtuse
if it is greater than 90 degrees, and a right angle if it is equal to
90 degrees. Using this information, write a C++ program that
accepts an angle, in degrees and displays of angle
corresponding to the degrees enters.

Introduction to Computing 56
Exercise: convert a flowchart to C++ program
#include <iostream>
using namespace std;
int main()
{
int i;
i = 10;
while (i >= 1) {
cout << i << " ";
i--;
}
return 0;
}
Introduction to Computing 57
Exercise: convert a flowchart
to C++ program

Introduction to Computing 58
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int celsius; double fahren;
cout << "DEGREES DEGREES\n";
cout << "CELSISUS FAHRENHEIT\n";
cout << "-------------- ------------------\n";
celsius = 5;
cout << setiosflags(ios::showpoint)<< setiosflags(ios::fixed) << setprecision(2);
while (celsius <= 50) {
fahren = (9.0/5.0)*celsius + 32.0;
cout << setw(4) << celsius << setw(13) << fahren << endl;
celsius = celsius + 5;
}
return 0;
}
Introduction to Computing 59
Introduction to Computing 60
Introduction to Computing 61

You might also like