Chapter#3

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 43

Fundamentals of Programming

Chapter 3 : Control Structure

2021

Computer Science & Engineering Program


The School of EE & Computing
Adama Science & Technology University
Outline
• Introduction – Control Structure
• Selection Statements
– Single selection if statement
– Two way selection if statement
– Multiway selection if and switch statement
– Nested if statements
• Repetition Statements
– Pre-test and Post-test Loops
– while, do while and for loops
– Nested loops
• Unconditional Statements
– break, continue, goto and exit

2
Control Structure
In 1966, computer scientists Corrado Böhm and Giuseppe Jacopini
demonstrated that all programs could be written using three
control structures: Sequence, Selection, and Repetition.
The sequence structure is the construct where one statement is
executed after another
The selection structure is the construct where statements can
executed or skipped depending on whether a condition evaluates
to TRUE or FALSE
The repetition structure is the construct where statements can be
executed repeatedly until a condition evaluates to TRUE or FALSE
The order in which statements are executed is called flow control
(or control flow).

To 3
Selection Structure

There are two selection structures in C++:


1. IF
a. Single-way Selection If
b. Two_way Selection If
c. Multi-way Selection If
2. SWITCH

4
One-way Selection If

The single if statement allow us to make the execution of a


statement or statements dependent upon a condition
being satisfied.
Syntax:
if (expression)
simple or block statement
First expression is evaluated. If the outcome is nonzero(or
true) then statement(simple or block) is executed.
Otherwise, the statement is skipped . Execution then
continues at the next statement.
5
Example

Write a C++ program that calculates and display the


absolute value of a number.

6
Two-way Selection If

C++ implements two-way selection using the if…else statement.


Syntax:
if (expression)
simple statement or block statement1
else
simple statement or block statement2
First expression is evaluated. If the outcome is nonzero(true)
then statement1(simple or block) is executed. Otherwise,
statement2 is executed . Execution then continues at the
next statement..
7
Example

Write a C++ program that takes a number from the user


and display whether it is odd or even

8
Multi-way Selection

Multi-way selection chooses among several


Alternatives. T

C++ uses two structures to implement F

multi-way selection: T

1. if…else if F

2. switch statement.

9
if…else if Statement
Syntax: Expression1 is evaluated. If it is
if (expression1) non zero, statement1(simple or
simple statement or block statement1 block) is executed otherwise
else if (expression2) statement1 is skipped and
simple statement or block statement2 expression2 is evaluated and if
it is non zero , statement2 is
else if (expression3)
executed otherwise statement2
simple statement or block statement3 is skipped and so on. If none of
. the expression is evaluated to
. non zero the statementLast
else if(expressionN) under the “else” is executed.
simple statement or block statementN Only the statement under one of
the condition or under the “else”
else will be executed.
simple statement or block statemtLast The ELSE part is optional.
10
Example

Write a program that determines the quadrant, given a user-input


angle(expect any angle). If the angle is 0, 90, 180, or 270, it lies on
the positive X-axis, the positive Y-axis, the negative X-axis, or the
negative Y-axis respectively.

11
Switch Statement
A switch statement is an alternative to the if-else chain for cases that involve
comparing an integer expression with a specific value. It uses four keyword:
switch, case, default and break. It has this general form:
switch ( integer expression)
First expression (called the switch tag) is
{ evaluated, and the outcome is compared to each
case constant1: of the numeric constants (called case labels), in
group of statements 1; the order they appear, until a match is found.
break; The statements following the matching case are
case constant2: then executed. Note the plural: each case may be
followed by zero or more statements (not just
group of statements 2;
one statement). Execution continues until either
break; a break statement is encountered or all
. intervening statements until the end of the
. switch statement are executed. The final default
case constantN: case is optional and is exercised if none of the
group of statements N; earlier cases provide a match.
Unlike the multi-way if, the switch can not be
break;
used for range value. The expression must
default: evaluates to integer and the value is compared
default group of statements with each of the constant for equality.
} 12
Example

Write a program that takes the type of vehicle (‘c’ or ‘C’ for car, ‘b’
or ‘B’ for bus and ‘t’ or ‘T’ for truck) and the hour the vehicle spent
in the parking lot and display the parking charge based on the rate
below:
Car $2 per hour
Bus$3 per hour
Truck $5 per hour

13
Nested if
An if-else statement can contain any valid C++ simple or compound
statements, including another if-else statement. Therefore, one or more
if-else statements can be included in either part of an if-else statement.
Including one or more if statements inside an existing if statement is
called a nested if statement. if (gender == 'M')
if (expression1) if (age < 21 )
if (expression2) policyRate = 0.05;
statement 1 else
else if (expression3) policyRate = 0.035;
else if (gender == 'F')
statement 2
if (age < 21 )
else policyRate = 0.04;
statement 3 else
else policyRate = 0.03;
statement 4
14
Example

Write a program to compute the real roots of a quadratic equation. Your


program should consider all possible cases.

15
Repetition- Concept

Repetition or loop is any program construction that repeats a


statement or sequence of statements a number of times. Each
repetition of the loop body is called an iteration of the loop.
The loop must be designed such that it ends after
some time of iteration. Otherwise the loop never
stops(see the side figure).
We must have a condition that controls the loop. Series of action
This condition or test is known as a loop control
expression or a loop limit test.

16
Pre-test and Post-test Loop
If the loop limit test(the test condition) is
checked before the loop starts, it is called
pre-test loop. ? T Actions
In each iteration, the loop control statement
is tested. If it is true. The loop actions are F
executed; otherwise, the loop is terminated. Pre-test loop

If the loop limit test is checked after loop


action is executed, it is called a post-test loop.
In each iteration, the loop actions are
executed. Next the loop limit test is Actions
executed. If it is true, a new iteration is
started; otherwise, the loop terminates.
?
In the Post-test loop, the loop actions are
executed at least once. F
Post-test loop
17
Initializing and Updating
Before a loop can start, some preparation usually done. This preparation
is called loop initialization. It is necessary to add a code that give an
initial value for a loop variable.
The control condition also must change from true(loop continue) to
false(loop terminate). Otherwise we would have an infinite loop. The
action that causes these changes is called loop update.
Updating is done at each iteration
Initialization

Initialization
Actions

T Update
? Actions Update
F T
?
Pre-test Loop 18
F Post-test Loop
Event-controlled and Counter-controlled Loop
The loop limit test expression can be two types: event-controlled and
counter-controlled loop.
In an event-controlled loop, an event changes the loop control
expression from true to false. The number of iteration is not known
beforehand.
If the number of iteration is known beforehand, it is called counter-
controlled loop.

Initialization Set Counter to 0

T Count T Increment
? Actions Update <n Actions
counter
F F

Pre-test Event-controlled Loop Pre-test Counter-controlled Loop

19
Loops in C++

There are three loop statements used in C++: the


while, the for and the do…while loop. The first two
are the pre-test loops, and the do-while loop is a
post-test loop.
Although all can be used for event-controlled and
counter-controlled loops, the while and do… while
loops are most commonly used for event-controlled
loops, whereas the for statement is usually used for
counter-controlled loop.
20
The while Loop
The general syntax for the while loop is:
while (loop limit test)
simple or block statement
while is a keyword.
Example:
int sum, i
sum=0; //initialization
i=1; // initialization
while(i <=100){
sum += i;
i++; //updating loop control variable
}
No semicolon is required for the while statement. The last semicolon belongs not
to the while statement but to the last statement within the while loop.
21
Example

Write a program that calculates class average of n


students for math's score where n is supplied by the
user. The score must be between 0 and 100

22
Example

Repeat the previous problem where the number of


student is not known in advance. Assume an entry
less than zero for score signifies end of entry for
score(sentinel value)

23
The for Loop
A for statement is a pre-test loop that uses three expression. The
first expression contains any initialization statements, the second
contains the loop limit test, and the third contains the updating
expression. The general syntax for the while loop is:
for (initializations ; loop limit test ; updatings)
simple or block statement
• The initializations are done only once at the first entry to the
loop.
• The loop limit test is executed before every iteration.
• The updatings are executed at the end of each iteration.
Using the comma operator you can initialize and update more than
one variable.
The initializations can be made out of the for structure and the
updating can be made inside the body of the loop. But the
semicolon must be there.
24
Example

Write a program that determines the number of


students for each grades ‘A’, ‘B’, ‘C’, ‘D’, ‘F’ in a
class of n students. n is to be supplied by the user.

25
Example

Repeat the previous problem where the number of


student is not known in advance. Assume an entry 0
for grade signifies end of entry for grade(sentinel
value)

26
The do…while Loop
The do…while loop is the post-test loop. The general
syntax for the do…while loop is:
do
simple or block statement
while (loop limit test);
do and while are keyword.
Note that unlike the while and for statement, the do…
while loop concluded with a semicolon.
The loop statements are executed at least once. It is
commonly used to validate data entry.
27
Example

Repeat the previous problem(Slide 25) but now the


scores must be validated to be between 0 and 100

28
Example

Write a program that determines the number of


students for each grades ‘A’, ‘B’, ‘C’, ‘D’, ‘F’ in a
class of n students where n is given by the user.

29
Example

Repeat the previous problem where the number of


student is not known in advance. Assume an entry 0
for grade signifies end of entry for grade(sentinel
value)

30
Nested Loop

For each of the C++ loop, the loop statement can be


any statement, even another loop. Including one or
more loop statements inside an existing loop
statement is called a nested loop.

31
Example

Write a program that determines the number of


students for each grades ‘A’, ‘B’, ‘C’, ‘D’, ‘F’ in a
class. The number of students is to be provided by
the user. The user is free to enter any character for
grade. Use do…while loop to validate the data.

32
Example

Write a program that prints the following pattern/


1****
12***
123**
1234*
12345

33
Example

Write a program that determines the square root of a


number. If the user enters a negative value, the user
must be informed of his mistake and requested
again. The program you write is also expected to run
several time until the user wants to quit.

34
Example

Write a program that determines the GCD and LCM


of two numbers. Propper input validation must be
done. The program you write is also expected to run
several time until the user wants to quit.

35
Unconditional Statement

Control statements that changes the flow


unconditionally are called unconditional selection
statement. Break, continue, exit, and goto.

36
The break Statement
A break statement may appear inside a loop (while, do…while, or
for) or a switch statement. It causes a jump out of these
constructs, and hence terminates them. After the break statement
executes, the program continues to execute with the first
statement after the structure.
A break statement only applies to the loop or switch immediately
enclosing it.
It is an error to use the break statement outside a loop or a switch.
Though simple and therefore preferred, using break may lead
difficult to read code.
Rewriting the loop without a break statement is always possible
by using an additional logical variable and adding it to the loop
condition
37
Example

Write a program that determines the sum of


numbers supplied by user. The numbers are known
to lie within -9999 and 9999. An entry out of this
range is considered as an end of entry(sentinel
value). Use break.

38
The Continue Statement

The continue statement terminates the current iteration of


a loop and instead jumps to the next iteration. It applies to
the loop immediately enclosing the continue statement
In while and do…while loops, the next iteration
commences from the loop condition. In a for loop, the
next iteration commences from the loop’s third
expression(update expression). For example, a loop which
repeatedly reads in a number.
It is an error to use the continue statement outside a loop.

39
Example

An experiment data contains range of positive n


values. The experimenter is interested in those
values that lies between 100 and 500. He/she wants
the average of the numbers in this range. Write a
program that calculates this sum. Use continue.

40
The goto Statement

goto allows to make an absolute jump to another point in the


program. Its syntax is:
goto destinationLabel;
destinationLabel is a label where control is transferred. A label is
made of a valid identifier followed by a colon (:).
For example
here: //this serves as label for the goto statement
You should use this feature with caution since its execution causes
an unconditional jump ignoring any type of nesting limitations.
Generally speaking, this instruction has no concrete use in
structured or object oriented programming.
41
Example

Write a program that determines the sum of list of


numbers supplied by user. The numbers are known
to lie within -9999 and 9999. An entry out of this
range is considered as an end of entry(sentinel
value). Use goto to implement the reptation.

42
The exit Function

Exit is not C++ statement. It is a function defined in the


stdlib library. To use it you must include stdlib.h
The purpose of exit is to terminate the current program
with a specific exit code. Its syntax is:
exit (int exitcode);
The exitcode is used by some operating systems and
may be used by calling programs. By convention, an exit
code of 0 means that the program finished normally and
any other value means that some error or unexpected
results happened.
43

You might also like