[go: up one dir, main page]

0% found this document useful (0 votes)
23 views46 pages

ES 1 ECE OOP MODULE 5 - Control Structures and Flowcharting

Module 5 covers control structure concepts and flowcharting, aiming to teach various programming control structures, including sequence, selection, and iteration. It emphasizes the importance of structured programming and provides examples of using if, if-else, and nested if statements in Python 3. Additionally, it introduces flowcharts as a visual tool for algorithm design and debugging.

Uploaded by

lalarixie
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)
23 views46 pages

ES 1 ECE OOP MODULE 5 - Control Structures and Flowcharting

Module 5 covers control structure concepts and flowcharting, aiming to teach various programming control structures, including sequence, selection, and iteration. It emphasizes the importance of structured programming and provides examples of using if, if-else, and nested if statements in Python 3. Additionally, it introduces flowcharts as a visual tool for algorithm design and debugging.

Uploaded by

lalarixie
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/ 46

OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 1 of 46

Control Structure Concepts & Flowcharting Module 5

At the end of this module, you are expected to:


1. Learn and explore the different control structure concepts
2. Apply an effective visual tool, like flowchart in program algorithm design
3. Examine and evaluate relational and Boolean expressions as applied to control structures
4. Discover the correct syntax on how to use the if, ifel... else constructs in Python 3 programs
5. Examine how to implement nested selection structures
6. Discover the relations of looping construct and indexed variables
7. Learn how to debug manually with the help of a flowchart, logic errors before and after a
program failure

Lesson 5.1 - Control Structure Concept

The default flow of control in programming is usually sequential. To alter this flow, the
facilities provided in most computers are:

 unconditional and conditional jumps (branches or selections)


 call to and return from functions and procedures (program blocks or modules)

Early programming languages provided essentially the same facilities:


label:
...
goto label
if (expression) goto label
call procedure(...)
... function(...) ...

Labels and functions might be numbered or named. Some languages do not use parameters,
instead they communicate via global variables. Many early languages also provided some sort of
for-loop, originally intended for stepping through arrays (also known as indexed variables or
tables).
However, bitter experience showed that allowing jumps to be made from any point of a
program to any other point is a bad idea; it disperses logically related parts of the program, it
obscures the flow of control so that you cannot decide which routes through the code are actually

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 1
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 2 of 46

possible, and it encourages jumps into the middle of otherwise working constructions, violating
their preconditions and generating untraceable bugs.
One part of language design became the search for higher-level control structures, to replace
as many uses of jumps as possible. Many different structures were proposed, often specific to a
particular programming style or problem. Many users were suspicious of this trend, believing that
power and efficiency were being lost.
Böhm and Jacopini proved that any program containing jumps can be converted to an
equivalent program using only loops and if-then-elses (selection or switch logic), provided some
extra Boolean variables are introduced. However, their proof did not show how to make best use
of these control constructs.
Edsger W. Dijkstra (a Dutch computer scientist) proposed that only three control constructs
should be used: sequence, selection and iteration, illustrated in Figure 5.1.

Figure 5.1 The Three Control Structure Constructs


Because each construct has exactly one entry and one exit, they may appear as one of the
boxes. Experience has shown that structured programming, using these constructs, does give
rise to efficient and understandable programs.

 Sequence Statement

Program codes are executed one after the other and is essentially built into programming
language like Python 3. This is known as the sequence control structure.

Example A.1. An example would be by using a graphical tool to build program, called flowchart
showing the sequence of finding the average of three test scores (see Figure 5.2),

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 2
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 3 of 46

# Taking 3 input from the user as integer


x = int(input("Enter value of x:"))
y = int(input("Enter value of y:"))
z = int(input("Enter value of z:"))

# Compute the sum & mean


sum = x + y + z
mean = sum / 3

# Print mean
print("Average = %.2f" % (mean))

Figure 5.2. Flowchart solution to Example A.1

NOTE: A flowchart is a graphical tool in building algorithm solution to a programming


problem (Pseudo code and NS (Nassi-Shneiderman) diagram are other tools). It makes
use of geometric shapes and arrows to represent a particular action or task in the
sequence it is drawn. For example, in Figure 4.4.2, the oval means termination - the start
or end of a task. The parallelogram represents an input/output operation. The box or
rectangle is a process, i.e., assigning values or Math expressions, and arrows point to
the next sequence of solution. These are symbols found in an application flowchart
(system flowcharts utilized other system specific symbols).

Example A.2. Find the area of a triangle (Figure 5.3) given its height and base. Give the Python
3 code based from the flowchart shown.

start

b, h

a = ½ bh
h

a
b

Figure 5.3. Given triangle with height (h) and end


base (b)

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 3
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 4 of 46

Solution using the Python 3 IDLE:

Example A.3. What is the area of circle (Figure 5.4) given its radius? Again, write the equivalent
Python 3 program.

start

a=3.1416 r2

end

Figure 5.4. A circle with radius (r)

Solution using the Python 3 IDLE:

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 4
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 5 of 46

NOTE: In Figure 5.3 and 5.4, two new flowcharting symbols are used:

manual entry, i.e., input from keyboard or input console

output display, i.e., console window or display monitor

 Selection Control Structure (switch/decision/selection construct)


The switch structure can be either:
a) if selection (one-way switch),
b) if-else selection (two-way switch) and,
c) if-elif-else (multiple switch).

A. if Statement

The if selection structure is a single-alternative condition that performs an action only when
the condition (using relational or Boolean expression) is true; otherwise the action is not
performed. The general form is:
if condition: In flowcharting, a diamond
box represents a
# execute this block of selection, a switch, or a
# code when condition is true juncture where the
outcome of a condition or
criterion being tested is
true or false.
To illustrate this refer to Figure 5.5.

Figure 5.5. One-way selection example

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 5
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 6 of 46

The condition or selection criteria used in an if statement can be any valid Python 3
expression (including an assignment expression). Examples of selection criteria are:

age > 40 idNum == 989 flag != done


2.0 > 3.3 hours <= 40 length >= 150
strValue == ”Hello” chrCode != ’X’
(voltage > 20) and (milliamp < 10) (i == j) or (a < b) or done

B. The if-else Statement

The if-else statement is a double-alternative conditional statement that executes either


one of the two alternatives depending on the condition if true or false. The general form is shown
in Figure 5.6.

Figure 5.6. Two-way switch or if-else structure

NOTE: The line of code(s) either in the if block, else block, or both, should always
be indented.

An example code implementation follows:


print(”Your average is %3.2f.” % (average))
if average < 70.0:
print(” Sorry, you did not pass.”)
else:
print(” Congratulations! You pass.”)

Python 3 provides an alternative to the code above using the following:


print(”You did ”, end=" ")
print("not pass" if average < 70.0 else "pass")

Different types of comparative operators are used in conditions, commonly broken down into
three categories: equality, relational, and logical (or, Boolean). All three are used to evaluate the
F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 6
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 7 of 46

relationship between two expressions or values. The values may be variables, constants,
numbers, strings, or the return value from a method call. Table 5.1 displays the equality, relational,
and logical operators in Python 3:

OPERATOR MEANING EXAMPLE RESULT TYPE


3 == 3 true
== equal to equality
2 == 5 false
6 != 4 true
!= not equal to equality
2 != 2 false
4<7 true
< less than relational
7<4 false
3 <= 5 true
<= less than or equal to relational
6 <= 5 false
8>7 true
> greater than relational
7>8 false
9 >= 9 true
>= greater than or equal to relational
9 >= 10 false
logical AND/logical multiplication (6 > 2) and (1 < 2) true
and logical
(both conditions must be true) (2 > 6) and (2 < 1) false
logical OR/logical addition (6 > 4) or (1 < 0) true
or logical
(one of the conditions must be true) (4 > 6) or (1 < 0) false
logical NOT/inversion/complement
not(2 == 8) true
not (condition must evaluate to false in logical
not(0 == 0) false
order to make the condition true)

Table 5.1. Operator results in selection structure

Python 3, C++ and C# (including Java) language is considered a freedom language, which
means there are no special rules for positioning white spaces such as blanks, tabs, and new lines.
The only limitation is that white space cannot be placed between the two characters of an
operator, such as == (see Table 5.1). In Python 3, tabs represent a block of codes used in
connection with the colon symbol (:).

The succeeding programs demonstrate the implementation of the different selection


structures.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 7
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 8 of 46

Example B.1. Find the highest among the given three distinct inputs.

… # input values of
I
… # a,b,c here
if a > b:
a, b, c
X = a
c>XT else:
X = b
T
a>b X=c if c > X:
X = c
… # output X here
X=b X=a x
NOTE: The circle in the flowchart (labeled
I) denotes an on-page connector showing
end continuity of the flow for a separate view
I on the same page shown.

Example B.2. Print the smallest number in a list of 3 decimal numbers.

… # input values of
… # a,b,c here
if a < b:
X = a
else:
X = b
if c < X:
X = c
… # output X here

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 8
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 9 of 46

Example B.3. Find the minimum and maximum data among three values.

A … # input values of
X, Y, Z
… # X,Y,Z here
T if X < Y:
Z < min min = X
T
X<Y else:
min = Z min = Y
if Z < min:
max = Y min = X min = Z
MAX = X MAX = Y Z> maxT if Z > max:
max = Z
max = Z
… # output min & max here
A
min, max

Nested if Statements

You can also include, or nest, if statements within another if statement. For example:

score = 100
print(”Result of your test: ”, end=” ”)
if score >= 70:
print(”Passed.”)
if score == 100:
print(”Perfect!”)
else:
print(”Failed.”)

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 9
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 10 of 46

You can nest, an unlimited number of if-else statements, like:


age = 16
if age>14:
if age>18:
print(”Adult”)
else:
print(”Teenager”)
else:
if age>0:
print(”Child”)
else:
print(”Invalid age!”)

C. The if-elif Statement

The if-elif statement can be used to decide among three or more criteria, see Figure
5.7.

Figure 5.7. Multiple selection construct

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 10
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 11 of 46

A sample program implementation is:


x = -1
y = 0
z = -2
print(”Smallest value: ”, end=” ”)
if x < y and x < z:
print(x)
elif y < z and y < x:
print(y)
elif z < x and z < y:
print(z)
else:
print()

REMEMBER: An if can have zero or more elif’s and they must come before
the last else, which is optional. Once an elif succeeds, none of the remaining
elif’s or else clause will be tested.

Two versions of implementing multiple selection construct are enumerated below.

# version 1
ch = char(input(”Pls. enter a character: ”))
if average < 60:
ch = ’F’;
else:
if average < 70:
ch = ’D’
else:
if average < 80:
ch = ’C’
else:
if average < 90:
ch = ’B’
else:
ch = ’A’
print(ch)

# version 2
ch = char(input(”Pls. enter a character: ”))
if average < 60:
ch = ’F’
elif average < 70:
ch = ’D’

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 11
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 12 of 46

elif average < 80:


ch = ’C’
elif average < 90:
ch = ’B’
else:
ch = ’A’
print(ch)

The menu system of an application can be considered in its simplest implementation, as


multiple selection construct. A program segment is given below.

print(”* * * * * * * * * * * * * *”)
print(”* DATA STRUCTURE *”)
print(”* * * * * * * * * * * * * *\n”)
print(” [ 0 ] Q U I T\n”)
print(” [ 1 ] TREES”)
print(” [ 2 ] HEAP” )
print(” [ 3 ] LINKED LIST” )
print(” [ 4 ] QUEUE” )
print(” [ 5 ] DEQUE” )
print(” [ 6 ] STACK\n” )
ch = char(input(”YOUR CHOICE <0-6>: ”))
if ch == ’0’:
goodbye()
elif ch == ’1’:
trees()
elif ch == ’2’:
heap()
elif ch == ’3’:
llist()
elif ch == ’4’:
queue()
elif ch == ’5’:
deque()
elif ch == ’6’:
stack()
else:
error()

The logical and operator, typically would be used for situations where you might want to
test more than one piece of data at the same time. For example, a program that checks for adult
males to register for selective service might compare the gender with a code for male, and the
age with a numeric value. In this case, each condition in its own set of parentheses (which is
optional) is written as:

if (gender == ’M’) and (age >= 18):

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 12
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 13 of 46

The logical or operator, typically would be used for testing the same piece of data in two
different ways. For example, a program that tests an age for possible child or senior discount
might compare the age against two different numeric values.

if (age < 18) or (age >= 60):

The logical not, typically would be used for testing a Boolean piece of data. For example, a
programmer might assign a Boolean true value to a variable named, done, in response to a user’s
input to quit the program. If done were not set, then processing would continue. The selection
statement might be:

if not done:

An important characteristic of the logical AND and OR is that if the left operand is sufficient to
decide the condition, the right side is never evaluated. For example, if the left side of the AND
operator, evaluates to false, the condition automatically is false and the right side need not be
evaluated. The left operand was sufficient to decide the condition.
The succeeding programs demonstrate the implementation of the different selection
structures.

SAQ #5

A. DIRECTIONS: In the following items, provide the correct answer(s).

1. Fill in the blanks to display ”Legal age” at the console when age is greater 17.

age = 24;
__ age __ 17:
print(”Legal age”)

ans:
age = 24;
if age > 17:
print(”Legal age”)

2. Which is the correct operator for equality testing?

a. != b. == c. >= d. <=

ans: b

3. Fill in the blanks to find the smaller of two variables.

x = 24
y = 77
__ x > y:
print(”%2d” % (y), end=” ”)
print(” is less than %2d” % (x))
F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 13
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 14 of 46

___:
print(”%2d” % __, end=” ”)
print(” is less than %2d” % __);

ans:
x = 24
y = 77
if x > y:
print(”%2d” % (y), end=” ”)
print(” is less than %2d” % (x))
else:
print(”%2d” % __, end=” ”)
print(” is less than %2d” % __);

4. What is the output of this code?

x = 8
y = ++x
if x > 5:
y -= 3
else:
y = 9
print(y)

ans: 5

5. How many nested if statements can an if statement contain?

a. only two b. three c. as many as you want d. none of these

ans: c

6. What is the output of this code?

num = 7
if num > 3:
print(”3”)
if num<5:
print(”5”)
if num==7:
print(”7”)

ans: 3

7. Fill in the blanks to test x when its value is either 10, 100 or ”No match”.

______ x == 10:
print(”Ten”)
______ x == 100:
F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 14
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 15 of 46

print(”Hundred”)
______ :
print(”No match”)

ans:
if x == 10:
print(”Ten”)
elif x == 100:
print(”Hundred”)
else:
print(”No match”)

8. What is the result of this code?

if (1==1) and (2+2>3):


print(”true”)
else:
print(”false”)

a. true false b. false c true d. none of these

ans: true

9. Fill in the blanks to print “Welcome”.

age = 15
money = 500
if (age>15) ____ (money>100):
______(”Welcome”)

ans:
age = 15
money = 500
if (age>15) and (money>100):
print(”Welcome”)

10. What is the result of this code?

if not True
print(”1”)
elif not(1+1 == 3):
print(”2”)
else:
print(”3”)

ans: 2

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 15
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 16 of 46

B. INSTRUCTIONS: Give the missing flowchart and/or Python 3 programs on the space
provided. Submit both the flowchart and the complete source code together with the screen
shots of program display at console window.

1. Display the average grade and the equivalent remark (passed, failed, conditional) given
prelim, midterm, and final grades.

P, M, F

AV = (P+M+F)/3.0

AV

T
AV <= 3.0

“PASSED”

AV <5.0
T

“CONDITIONAL”

“FAILED””

2. Enter the age of two persons. Display the difference of their ages.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 16
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 17 of 46

“First Person’s
Nickname:”,

NName1

“First Person ‘s age:”,

Age1

“Next Person’s
Nickname:”,

NName2

“Next Person ‘s age:”,

Age2

Diff = Age1 – Age2

NName1 ”
T you have the
Diff = = 0
same age as”
NName2

Diff > 0
T
NName1 “you’re”, Diff,
“years older than”NName2

NName2 “you’re”, -1*Diff, “years


older than”NName1
X

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 17
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 18 of 46

2. Determine if an input alphabet letter is vowel or not.

alph = input(”Enter a letter: ”)

# check if vowel or consonant


if alph in [’a’,’e’,’i’,’o’,’u’,
’A’,’E’,’I’,’O’,’U’]:
print(”VOWEL”)
else:
print(”NOT A VOWEL”)

4. In a game program, the scores of players A and B are stored in variables score_a and
score_b. Assuming that the player with the larger score wins, write a sequence of
conditional statements that prints out "A won", "B won", or "Game tied". Draw the flowchart
and write the corresponding C# program.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 18
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 19 of 46

ANSWERS TO SAQ #5

B. 1. Display the average grade and the equivalent remark (passed, failed, conditional) given
prelim, midterm, and final grades.

3. Enter the age of two persons. Display the difference of their ages.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 19
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 20 of 46

4. Determine if an input alphabet letter is vowel or not.

alph

alph in [ ’a’ , ‘e’, “VOWEL”


‘i’, ‘o’ ,‘u’, ‘A’,
T
‘E’,’I’,’O’,’U’]

“NOT A VOWEL”

5. In a game program, the scores of players A and B are stored in variables score_a and
score_b. Assuming that the player with the larger score wins, write a sequence of
conditional statements that prints out "A won", "B won", or "Game tied". Draw the flowchart
and write the corresponding program.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 20
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 21 of 46

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 21
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 22 of 46

In Activity No. 5.1


the
Lab Selection Structures Implementation

Get ready with your computer or Android device and explore the different selection
structures implementation using Python 3.

In this hands-on activity you will design complete programs given the following tasks. Submit
all the completed program together with the screen shots of the program output displayed at the
Console window.

1. Design, compile and run a program that will input five numbers and display whichever has the
lowest value.

2. Design, compile and run a program that decides and prints “divisible” if an input value is
divisible by 10. Otherwise, print “Not Divisible”.

3. Write a program if for example, the input: 6 8 2028 prints the date June 8, 2028.

4. A program tests an input temperature and display corresponding output based on the following
information:

Temperature Output
Less than zero ICE
Between zero and one hundred WATER
Exceeds one hundred STEAM
5. Write a program that will ask the user to input a letter ’m’ or ’f’ and then it will display ”Hello
Sir” if the input is ’m’ otherwise, ”Hello Madam”.

6. Write a program that will determine the grade of the student based on the rating scale as
follows:

Grade Rating Grade Rating


> 90 A+ 51-60 C
81-90 A 41-50 D
71-80 A- < 41 F
61-70 B

7. Write a program that will check and print if the person is a regular passenger, student or
senior citizen to determine the fare of the person in a passenger boat. If it is number 1 =
Regular passenger, 2 = Student passenger and lastly 3 = Senior Citizen passenger.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 22
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 23 of 46

8. Write a program that will determine the salary of an employee based on his or her rank
as follows:

Rank Salary (Php) Rank Salary (Php)


1 70,000 4 50,000
2 65,000 5 35,000
3 60,000 Below 5 20,000

RATING SHEET
(for submission to be included in every problem solution/answer)
Student Name:……………………………………….. Score:……………..
Course/Section:……………………………………… Date Submitted:……………..

Lab Activity 5.1 Selection Structures Implementation

1. Design, compile and execute complete program implementing


Intended selection structures.
Learning 2. Debug and re-test correctness of program solution using test cases.
Outcome 3. Identify and address program bugs.

Problem Number/
Page Number

EVALUATION RUBRICS FOR ACTIVITY AND CHALLENGE


Progressing Difficulty
Meeting
Towards Meeting Meeting Achieved
Criteria Expectations
Expectations Expectations Score
(7-10 pts.)
(3-6 pts.) (0-2 pts.)
1. Algorithm Correct pseudo Some correct and Incorrect or
code or flowchart incorrect illogical flowchart
using required flowcharting to show correct
control structures symbols used. program solution.
utilized, completed, Incomplete and/or
and clearly incorrect branching
depicted. construct.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 23
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 24 of 46

2. Specifications The program The program The program


and solution works and solution produces solution is
Functionality produces the correct results but producing
correct results and does not display incorrect result or
displays them them correctly. it contains several
correctly. It also syntax errors.
meets most of the
other
specifications.
3. Readability and The submitted The submitted The submitted
Documentation code is code is readable code is poorly
exceptionally well only by someone organized and
organized and the who knows what it quite difficult to
logic very easy to is supposed to be follow logically.
follow. The accomplishing
documentation is logically.
well written and
clearly explains
what the code is
supposed to
accomplish and
how it is attained.
4. Test Cases Actual sample Actual sample Actual sample
program runs program runs program runs
contain all correct contain some contain incorrect
test case output correct case output test case output
results results results.
Total Score:

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 24
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 25 of 46

CHALLENGE #5.1 (SUBMIT AS PART OF THE HANDS-ON ACTIVITY)


INSTRUCTIONS: Your engineering courses exposed you to some of the most exciting and
challenging problem solving experiences. With these skills and as a review (early review for board
exam), solve the following programming problems:
Engineering P5.1.1 Write a program that prompts the user for a wavelength value and prints
a description of the corresponding part of the electromagnetic spectrum, as given in Table 7.

Engineering P5.1.2 Repeat Exercise P5.1.1, modifying the program so that it prompts for
the frequency instead.

Engineering P5.1.3 Repeat Exercise P5.1.1, modifying the program so that it fist asks the
user whether the input will be a wavelength or a frequency.

Engineering P5.1.4 A minivan has two sliding doors. Each door can be opened by either a
dashboard switch, its inside handle, or its outside handle. However, the inside handles do not
work if a child lock switch is activated. In order for the sliding doors to open, the gear shift must
be in park, and the master unlock switch must be activated.
Your task is to simulate a portion of the control software for the vehicle. The input is a sequence
of values for the switches and the gear shift, in the following order:
• Dashboard switches for left and right sliding door, child lock, and master unlock (0 for off or 1
for activated)
• Inside and outside handles on the left and right sliding doors (0 or 1)
• The gear shift setting (one of P N D 1 2 3 R).

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 25
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 26 of 46

A typical input would be 0 0 0 1 0 1 0 0 P.


Print “left door opens” and/or “right door opens” as appropriate. If neither door opens, print “both
doors stay closed”.

Engineering P5.1.5 Sound level L in units of decibel (dB) is determined by L = 20 log10(p/p0)


where p is the sound pressure of the sound (in Pascals, abbreviated Pa), and p0 is a reference
sound pressure equal to 20 x10–6 Pa (where L is 0 dB). The following table gives descriptions for
certain sound levels.
Threshold of pain 130 dB
Possible hearing damage 120 dB
Jack hammer at 1 m 100 dB
Traffic on a busy roadway at 10 m 90 dB
Normal conversation 60 dB
Calm library 30 dB
Light leaf rustling 0 dB

Write a program that reads a value and a unit, either dB or Pa, and then prints the closest
description from the list above.

Engineering P5.1.6 The electric circuit shown below is designed to measure the temperature
of the gas in a chamber.

Suppose the voltmeter voltage is constrained to the range Vmin = 12 volts ≤Vm ≤Vmax = 18 volts.
Write a program that accepts a value of Vm and checks that it’s between 12 and 18. The program

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 26
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 27 of 46

should return the gas temperature in degrees Celsius when Vm is between 12 and 18 and an error
message when it isn’t.

Engineering P5.1.7 Crop damage due to frost is one of the many risks confronting farmers.
The figure below shows a simple alarm circuit designed to warn of frost. The alarm circuit uses a
device called a thermistor to sound a buzzer when the temperature drops below freezing.
Thermistors are semiconductor devices that exhibit a temperature dependent resistance
described by the equation

where R is the resistance, in , at the temperature T, in °K, and R0 is the resistance, in , at the
temperature T0, in°K.  is a constant that depends on the material used to make the thermistor.

The circuit is designed so that the alarm will sound when

The thermistor used in the alarm circuit has R0 = 33,192  at T0 = 40 °C, and  = 3,310 °K.
(Notice that  has units of °K. Recall that the temperature in °K is obtained by adding 273° to the
temperature in °C.) The resistors R2, R3, and R4 have a resistance of 156.3 k = 156,300 .
Write a C++ program that prompts the user for a temperature in °F and prints a message indicating
whether or not the alarm will sound at that temperature.

Engineering P5.1.8 A mass m = 2 kilograms is attached to the end of a rope of length r = 3


meters. The mass is whirled around at high speed. The rope can withstand a maximum tension
of T = 60 Newtons. Write a program that accepts a rotation speed v and determines if such a
speed will cause the rope to break. Hint: T= mv2/ r2.
F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 27
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 28 of 46

Engineering P5.1.9 A mass m is attached to the end of a rope of length r = 3 meters. The
rope can only be whirled around at speeds of 1, 10, 20, or 40 meters per second. The rope can
withstand a maximum tension of T = 60 Newtons. Write a program where the user enters the
value of the mass m, and the program determines the greatest speed at which it can be whirled
without breaking the rope. Hint: T= mv2/ r.

Engineering P5.1.10 The average person can jump off the ground with a velocity of 7 mph
without fear of leaving the planet. However, if an astronaut jumps with this velocity while standing
on Halley’s Comet, will the astronaut ever come back down? Create a program that allows the
user to input a launch velocity (in mph) from the surface of Halley’s Comet and determine whether
a jumper will return to the surface. If not, the program should calculate how much more massive
the comet must be in order to return the jumper to the surface.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 28
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 29 of 46

 Program Loop or Iteration


In Python 3 there are two looping or iterative statements:
1. while() (pre-test or test first loop construct)
2. for() (pre-determined loop w/ counter)

Program Repetition Using while() Statement

The while() statement allows you to specify that a task is to be repeated while certain
condition remains true. Figure 5.8 and 5.9 illustrate pre-test and post-test looping construct
respectively.

Figure 5.8. The pre-test loop or while() construct to find the quotient and remainder of two
integers

for k in range(1,5):
print(k)

Figure 5.9. The for loop construct using range function

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 29
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 30 of 46

In Figure 5.9, a counter-controlled repetition is illustrated to print the range of integers from
1 to 5. The range() function returns a sequence of numbers, starting from 1 and increments by 1
(by default), and stops before a specified number. The syntax of range function is generally
defined as follows:

range(start, stop, step)


Parameter Values (start, stop & step are parameters described below.

start Optional. An integer number specifying at which position to start.


Default is 0

stop Required. An integer number specifying at which position to stop


(not included).

step Optional. An integer number specifying the incrementation. Default


is 1

This technique uses a variable called a counter (i.e., k) to control the number of times the
body of the loop will execute (also known as the number of iterations of the loop). Since the step
or increment is default as 1, then the k is incremented by 1 (or, k++) and is printed until it reaches
the final value 5.

Counter-controlled repetition is often called definite repetition because the number of


repetitions is known before the loop begins executing and is defined by the parameters of the
range() function. In Figure 5.9, repetition terminates when the counter exceeds 5.

Another way to terminate a loop is through a sentinel value (also called a signal value,
a dummy value or a flag value) to indicate "end of data entry." For example, a user types items
in until all legitimate values have been entered. The user then types the sentinel value to indicate
that the last data has been entered. Sentinel-controlled repetition is often called indefinite
repetition because the number of repetitions is not known before the loop begins executing.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 30
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 31 of 46

break and continue Statements in a while() Loop

Figure 5.10. Flowchart of break and continue statements in Python 3

In addition to the selection and repetition statements, Python 3 provides break and
continue statements to alter program flow.
The break statement, when executed in a looping or switch statement, causes immediate
exit from that statement. Program execution continues with the next statement. Common uses
of the break statement are to escape early from a loop. The flowchart to illustrate this escape is
shown in the left diagram of Figure 5.10.
The continue statement, when executed in any of the repetition statements (including the
for statement to be discussed later), skips the remaining statements in the body of that statement
and proceeds with the next iteration of the loop. The flowchart to illustrate continue is shown in
the right diagram of Figure 5.11. In while statement, the loop-continuation test evaluates
immediately after the continue statement executes. (In the for statement, the increment
expression executes, then the loop-continuation test evaluates.)

Figure 5.12. How continue statement works in Python

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 31
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 32 of 46

Take note that break escapes out of the loop while continue skips the rest of the body of
the loop and proceeds to the next iteration of the loop (see Figure 5.12).

Here are partial programs to demonstrate the use of break and continue statement in a
looping construct.

# break statement inside the loop # use of continue statement inside loop
for ch in "string": for ch in "string":
if ch == "i": if ch == "i":
break continue
print(ch) print(ch)
print("The end") print("The end")
Program output: Program output:
s s
t t
r r
The end n
g
The end

The succeeding programs demonstrate other implementation of the looping or iteration


structures.

This while loop repeatedly executes a block of codes (also, called body of the loop) as long as
a given condition is true. For example:
i = 0
while ++i < 4:
print(i)

/* Outputs
1
2
3 */

The compound arithmetic operators can be used to further control the number of times a loop
runs. For example:
num = 1
while num < 6:
print(num)
num += 2

/* Outputs
1
3
5 */
F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 32
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 33 of 46

Nested Loops
Nested loops are two or more loops contained within an outer loop. For example:

// 10 x 10 multiplication table
for r in range(1,10):
for c in range(1,10):
print(” %3d” % (r*c), end=” ”)
print()

Using nested loops, you will display a pyramid of a certain height using an asterisk symbol
“*”. The solution to this (prior to programming code implementation) is using an algorithm; a step-
by-step solution in performing any programming task. A nested loop pseudo code to draw the
pyramid out of asterisk are:
1. The outermost loop iterates n times (n is the height of the pyramid) through each row of
the pyramid that contains two inner loops.
1.1 The first inner loop displays the spaces needed before the asterisk.
1.2 The second inner loop displays the required number of asterisk for each row,
calculated based on: 2*looping variant - 1 (looping variant is the current row).
1.3 Execute a carriage return (move to next line of console screen).
2. End of loop
The corresponding program and output display in shown in Figure 5.13.

Figure 5.13. Using nested loops to draw a pyramid out of asterisks

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 33
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 34 of 46

The for in Loop and Indexed Variables or Arrays or Lists

You can use the for in loop to iterate through all the elements of an array. The syntax is:
for variable in array:
#statements

• Variable: This is a variable to store one at a time, the elements of the array listed with
some type of data.
• Array: An indexed variable, or array is a linear list of data, previously declared to hold any
type of data and populated during or prior to the loop execution. Figure 5.14 are two ways
to declare an array. The second method is combining array declaration and initialization
of elements. You are allowed only one of these two methods in order to declare an array.

Figure 5.14. Syntax of declaring and initializing an array.

Figure 5.14 shows an array of strings of car brands. This array contains 5 elements. A program
refers to any one of these elements by giving the name of the array followed by the position
number of the particular element in square brackets ([]), like cars[2] with an assigned value
”BMW”. The elements of cars are cars[0] (read "cars sub zero"), cars[1], cars[2] and so on.
The highest subscript is 2, which is 1 less than the array size of 3 (array size is the total number
of its elements and readily available through the function len(), i.e. x = len(cars)). Array
names follow the same conventions as other C# variable names.

Here is an example of for in loop to iterate over an array named scores.

scores = [88, 34, 50, 12]


total = 0
for in elem in scores:
total += elem # this find the total of all elements in array
ave = total/len(scores)

The partial program listed below, stores some scores using an array and computes the
average score of these list of scores. Actually, there are a number of functions available for lists
such as max() (returns the largest element), min() (returns the smallest element) and sum()
(returns the sum of all elements). For example:
arr = [2,4,7,1]
print(sum(arr)) # outputs 14
print(min(arr)) # outputs 1
print(max(arr)) # outputs 7

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 34
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 35 of 46

Other Python List Functions (or, Methods)

Python has a lot of list methods that allow us to work with lists. For example, if you want
to add a single item to the end of the list, you can use the append() function. Others are listed
below.

Python List append()


Add a single element to the end of the list

Python List clear()


Removes all Items from the List

Python List copy()


returns a shallow copy of the list

Python List count()


returns count of the element in the list

Python List extend()


adds iterable elements to the end of the list

Python List index()


returns the index of the element in the list

Python List insert()


insert an element to the list

Python List pop()


Removes element at the given index

Python List remove()


Removes item from the list

Python List reverse()


reverses the list

Python List sort()


sorts elements of a list

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 35
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 36 of 46

ASSIGNMENT #5.2 (SUBMIT AS PART OF THE HANDS-ON ACTIVITY)

INSTRUCTIONS: Given the flowchart write the equivalent Python 3 program on the space
provided. Submit both the flowchart and the complete source code together with the screen shots
of program display at console window.

1. Using pre-test loop and a counter, display the numbers 1, 2, 3, …, 10.

(Place your program here)

2. Using for() loop, print all values between 1 and 10, inclusive.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 36
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 37 of 46

(Place your program here)

In Activity No. 5.2


the
Lab Looping Structures and Single Dimension Arrays

In this hands-on activity you will design complete programs using loops and arrays. Submit
all the completed program together with the screen shots of the program output displayed at the
Console window.

1. Display a series of numbers from 1.0 to 9.5 in increments of 0.5 and from 100 down to 0 in
increments of 5.

2. Using while loop, display odd and even numbers separately from -20 to +20.

3. Input a starting number and an ending number and based from this information print all the
values between the two numbers.

4. Ask the user to input first and second values and based from these range of values, display
all odds, even, and prime numbers.

5. Using for in loop, display the names of the days in a week.


F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 37
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 38 of 46

CHALLENGE #5.2 (SUBMIT AS PART OF THE HANDS-ON ACTIVITY)


INSTRUCTIONS: A few engineering problems are listed below. Solve the following problems
using Python 3:

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 38
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 39 of 46

RATING SHEET
(for submission to be included in every problem solution/answer)
Student Name:……………………………………….. Score:……………..
Course/Section:……………………………………… Date Submitted:……………..

Lab Activity 5.2 Selection Structures and Single Dimension Arrays

1. Design, compile and execute complete program implementing looping


Intended structures and single dimension arrays.
Learning 2. Debug and re-test correctness of program solution using test cases.
Outcome 3. Identify and address program bugs.

Problem Number/
Page Number

EVALUATION RUBRICS FOR ACTIVITY AND CHALLENGE

Progressing Difficulty
Meeting
Towards Meeting Meeting Achieved
Criteria Expectations
Expectations Expectations Score
(7-10 pts.)
(3-6 pts.) (0-2 pts.)
1. Algorithm Correct pseudo Some correct and Incorrect or
code or flowchart incorrect illogical flowchart
using required flowcharting to show correct
control structures symbols used. program solution.
utilized, completed, Incomplete and/or
and clearly incorrect
depicted. branching/looping
construct.
2. Specifications The program The program The program
and solution works and solution produces solution is
Functionality produces the correct results but producing
correct results and does not display incorrect result or
displays them them correctly. it contains several
correctly. It also syntax errors.
meets most of the
other
specifications.
3. Readability and The submitted The submitted The submitted
Documentation code is code is readable code is poorly
exceptionally well only by someone organized and
organized and the who knows what it

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 39
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 40 of 46

logic very easy to is supposed to be quite difficult to


follow. The accomplishing follow logically.
documentation is logically.
well written and
clearly explains
what the code is
supposed to
accomplish and
how it is attained.
4. Test Cases Actual sample Actual sample Actual sample
program runs program runs program runs
contain all correct contain some contain incorrect
test case output correct case output test case output
results results results.
Total Score:

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 40
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 41 of 46

Recursion
Objectives:

 To understand that complex problems may have a simple recursive solution.


 To learn how to formulate programs recursively.
 To understand and apply the three laws of recursion.
 To understand recursion as a form of iteration.
 To implement the recursive formulation of a problem.
 To understand how recursion is implemented by a computer system.

Introduction to Recursion

Python 3 programs and functions are generally executed by calling one another in organized
structures of hierarchy. Many programming problems implement function calls through iterative
structure meaning, using repetition or loop construct. For some problems, it is useful to have
functions call themselves – these functions are known as recursive functions.

Recursive problem solving approaches have a number of common elements – the simplest case
and the recursive case. The recursive function knows only how to solve the simplest case, or
commonly called base case(s), wherein the function simply returns a result. The more complex
solution, when derived, is divided into conceptual pieces: a piece that the function knows how to
carry out the solution and a piece that the function cannot find an immediate result or outcome.
To make recursion feasible, the latter piece must resemble the original solution – that is, it must
be a slightly simpler or smaller version of the original. Because of this resemblance, the function
invokes (or, calls) a fresh copy of itself to work on the smaller piece and this is referred to as a
recursive call, or a recursive step.

The recursive step executes while the original call to function is still open, i.e., it has not yet
terminated the execution and keeps on dividing (more precisely, nesting) into a new sub-call to
itself again and again until encountering the base case(s). At the base case(s) the return
statement transfers back the control to the latest recursive call in a chain of nested calls to arrive
at a final passed back to the original caller most probably, the main module.

An example application is the factorial of n (or, n!, read as “n factorial”), where n is any
nonnegative integer big enough for the compiler and memory to handle, given as

n! = n∙ (n-1) ∙ (n-2) ∙ ∙ ∙ 3 ∙ 2 ∙ 1

For example, 4! = 4∙3∙2∙1 = 24; 1! = 1; and 0! = 1.

The factorial solution by this formula, can be calculated iteratively (this means, non-recursively)
using for loop as follows.

# Python code to demonstrate iterative method


# to compute n factorial (n is non-negative whole number)
F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 41
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 42 of 46

n = 23
fact = 1
for i in range(1,n+1):
fact = fact * i

print (f"The factorial of {n} is : ",end="")


print (fact)

Output of this program is:


The factorial of 23 is : 25852016738884976640000
A built-in Math function can be utilized to solve the same problem:

# Python code to demonstrate math.factorial()


import math
n = 23
print (f"The factorial of {n} is : ", end="")
print (math.factorial(n))

The recursive solution can then be derived using

n! = n ∙ ( n – 1 )!

Because when n=4 (see Figure 5.15),

4! = 4 ∙ 3 ∙ 2 ∙ 1

= 4 ∙ 3!  3! = 3 ∙ 2!  2! = 2 ∙ 1!  1! = 1 ∙ 0! = 1

Figure 5.15. The recursive solution to factorial of 4 (4!).

The recursive definition of a function called recur_facto() should be:

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 42
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 43 of 46

# Factorial of a number using recursion


def recur_facto(n):
if n == 1:
return n
else:
return n*recur_facto(n-1)
num = 4
# check if the number is negative
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
print("The factorial of", num, "is", recur_facto(num))

Another recursive application is in the Fibonacci series: 0, 1, 1, 2, 3, 5, 8, 13, 21, … that can be
defined as follows:

Fibonacci(0) = 0 or, Fibonacci(1) = 1 (may be regarded as the base cases)

Fibonacci(n) = Fibonacci(n–1) + Fibonacci(n–2)

The recursive definition of a function called fibo() should be:

# Function for nth Fibonacci number


def fibo(n):
if n < 0:
print(f"Value of {n} should NOT be negative!")
# First Fibonacci number is 0
elif n == 0:
return 0
# Second Fibonacci number is 1
elif n == 1:
return 1
else:
return fibo(n-1)+fibo(n-2)

# Driver Program
print(fibo(3))

The illustration below in Figure 5.16 enumerates the set of recursive call to function fibo(3).

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 43
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 44 of 46

Figure 5.16. The recursive solution to the 3rd Fibonacci number.

An iterative solution to finding the nth Fibonacci sequence is given below in Program Listing.

# Function for nth fibonacci number using iterative method


# Taking 1st two fibonacci numbers as 0 and 1
def iter_fibo(n):
if n < 0:
print(f"Value of {n} should NOT be negative!")
first = 0
second = 1
fibo=0
for c in range(n+1):
if ( c <= 1 ):
fibo = c
else:
fibo = first + second
first = second
second = fibo
return fibo
# Driver Progra3
print(iter_fibo(3))

Lastly, you can solve Fibonacci number series using the formula

1  1  5   1  5  
n n

Fibon      
5  2   2  
 

If n=3 then,

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 44
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 45 of 46

1  1  5   1  5  
3 3

Fibo3     
5  2   2  
 
 3.236 3  - 1.236 3 
 0.447       0.4474.236  0.236   1.999  2
 2   2  

This is the Python 3 program:

# To find the n-th Fibonacci Number using formula


from math import sqrt
# import square-root method from math library
def nthFib(n):
# compute the n-th fibonacci number
res = (((1+sqrt(5))**n)-((1-sqrt(5)))**n)/(2**n*sqrt(5))
# format and print the number
print(int(res),'is',str(n)+'th fibonacci number')
# driver code
nthFib(3)

LAB. ACTIVITY #5.3


1. (H-O Activity 1) Use the given function funcWhat() in a Python 3 program and make a
conclusion about its purpose.

def funcWhat(m, n):


if(n==1):
return m
else:
return m + funcWhat(m,n-1)

2. (H-O Activity 2) Write a recursive function findSum(), that calculates the sum of successive
integers starting at 1 and ending at n. For example findSum(n) would perform the summation
1 + 2 + 3 +,...,+ (n-2) + (n-1) + n.

ASSIGNMENT #5.3
INSTRUCTIONS: Build and run a Python 3 program to perform the following tasks. Submit in
pdf format Arial font size 11 single spaced the codes and program runs at the Console window.
Euclid’s algorithm for finding the greatest common denominator (GCD) of two positive integers,
M and N is to satisfy the following condition of the base case(s) and recursive case, respectively:

1. GCD(M,N) is N iff N<=M and N divides M


2. GCD(M,N) is GCD(N,M) iff M<N
3. GCD(M,N) is GCD(N, remainder of M divided by N

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 45
OOP MODULE 5 - Control Structure Concepts & Flowcharting Page 46 of 46

Build and run the Python 3 program to implement this algorithm.

F.M.Fernando (NOTICE :Reproduction of this material is unauthorized without the approval of the author.) 46

You might also like