Self-Instructional Manual (SIM) For Self-Directed Learning (SDL)
Self-Instructional Manual (SIM) For Self-Directed Learning (SDL)
Course Outline…………………………………………………………………………………………. 4
Course Information……………………………………………………………………………………. 7
Topic/ Activity
Unit Learning Outcomes- Unit 1…………………………………………………………………. 8
Big Picture in Focus: ULO-1a…………………………………………………………………..….. 8
Metalanguage…………………………………………………………………………………... 8
Essential Knowledge………………………………………………………………………… 10
Self-Help………………………………………………………………………………………….. 13
Let’s Check……...……………………………………………………………………………….. 13
Let’s Analyze...………………………………………………………………………………….. 14
In a Nutshell…………………………………………………………………………………….. 14
Q & A List ……………………………………………………………………………………...… 14
Big Picture in Focus: ULO-1b…………………………………………………………………..….. 15
Metalanguage………………………………………………………………………………….. 15
Essential Knowledge………………………………………………………………………… 15
Self-Help………………………………………………………………………………………….. 22
Let’s Check……...……………………………………………………………………………….. 22
In a Nutshell…………………………………………………………………………………….. 23
Q & A List ………………………………………………………………………………………... 23
Big Picture in Focus: ULO-1c…………………………………………………………………..….. 24
Metalanguage………………………………………………………………………………….. 24
Essential Knowledge………………………………………………………………………… 24
Self-Help………………………………………………………………………………………….. 31
Let’s Check……...……………………………………………………………………………….. 32
In a Nutshell…………………………………………………………………………………….. 33
Q & A List ………………………………………………………………………………………... 34
Big Picture in Focus: ULO-2a…………………………………………………………………..….. 35
Metalanguage………………………………………………………………………………….. 35
Definition of Terms…………………………………………………………………………. 35
Essential Knowledge………………………………………………………………………… 37
Self-Help………………………………………………………………………………………….. 31
Let’s Check……...……………………………………………………………………………….. 41
Q & A List ………………………………………………………………………………………... 43
Big Picture in Focus: ULO-2b…………………………………………………………………..….. 44
Metalanguage………………………………………………………………………………….. 44
Essential Knowledge………………………………………………………………………… 44
Self-Help………………………………………………………………………………………….. 51
Let’s Check……...……………………………………………………………………………….. 51
In a Nutshell…………………………………………………………………………………….. 55
Q & A List ………………………………………………………………………………………... 55
2
Laboratory Rubric……………………………………………………………………………. 56
Big Picture in Focus: ULO-2c…………………………………………………………………..….. 57
Metalanguage………………………………………………………………………………….. 57
Essential Knowledge………………………………………………………………………… 57
Self-Help………………………………………………………………………………………….. 59
In a Nutshell…………………………………………………………………………………….. 59
Let’s Check……...……………………………………………………………………………….. 60
Q & A List ………………………………………………………………………………………... 69
Laboratory Rubric……………………………………………………………………………. 70
Big Picture in Focus: ULO-3a…………………………………………………………………..….. 71
Metalanguage………………………………………………………………………………….. 71
Essential Knowledge………………………………………………………………………… 71
Self-Help………………………………………………………………………………………….. 77
In a Nutshell…………………………………………………………………………………….. 77
Let’s Check……...……………………………………………………………………………….. 78
Q & A List ………………………………………………………………………………………... 79
Laboratory Rubric……………………………………………………………………………. 80
Big Picture in Focus: ULO-3b…………………………………………………………………..….. 81
Metalanguage………………………………………………………………………………….. 81
Essential Knowledge………………………………………………………………………… 81
Let’s Check……...……………………………………………………………………………….. 84
Self-Help………………………………………………………………………………………….. 85
Q & A List ………………………………………………………………………………………... 85
Laboratory Rubric……………………………………………………………………………. 86
Big Picture in Focus: ULO-3c…………………………………………………………………..….. 87
Metalanguage………………………………………………………………………………….. 87
Essential Knowledge………………………………………………………………………… 87
Let’s Check……...……………………………………………………………………………….. 90
Self-Help………………………………………………………………………………………….. 91
In a Nutshell…………………………………………………………………………………….. 91
Q & A List ………………………………………………………………………………………... 92
Laboratory Rubric……………………………………………………………………………. 93
3
Course Outline: EDP101/L- Computer Fundamentals and Programming
Email: [email protected]
Mobile: 09367826047
Requisites: None
4
Assessment Task Submission The first assessment task (examination) shall be given on
the 3rd week subsequent to the first day of class. The
remaining assessment tasks shall be handed every after
two (2) weeks of each examination schedule. The
assessment paper shall be attached with a cover page
indicating the name of the course coordinator, date of
submission, and name of the student. The document
should be submitted on the same day through e-mail or
Blackboard LMS. It is also expected that you have already
paid your tuition and other fees before the submission of
the assessment task.
Penalties for Late The score for an assessment item submitted after the
Assignments/Assessments designated time on the due date, without an approved
extension of time, will be reduced by 5% of the possible
maximum score for that assessment item for each day or
part day that the assessment item is late.
Return of Assignments/ Assessment tasks will be returned to you two (2) weeks
Assessments after the submission with a mark and feedback. This will
be returned by email or via Blackboard portal.
For group assessment tasks, the course coordinator will
require some or few of the students for online or virtual
sessions to ask clarificatory questions to validate the
originality of the assessment task submitted and to ensure
that all the group members are involved.
Re-marking of Assessment Papers and You should request in writing addressed to the program
Appeal coordinator your intention to appeal or contest the score
given to an assessment task. The letter should explicitly
explain the reasons/points to contest the grade. The
program coordinator shall communicate with the students
on the approval and disapproval of the request.
If disapproved by the course coordinator, you can elevate
your case to the program head or the dean with the
original letter of request. The final decision will come from
the dean of the college.
5
Grading System All culled from BlackBoard sessions and traditional
Contact:
Course discussions/exercises – 30% st
1 formative assessment – 10% nd
2 formative assessment – 10% rd
3 formative assessment – 10%
6
Help Desk Contact CEE Blackboard Administrator:
CEE:
Frida Santa O. Dagatan
Email: [email protected]
Phone: +63 9055 267834
GSTC:
Ronadora E. Deala, RPsy, RPm, RGC, LPT
Email: [email protected]
Phone: +63 921 2122846
Silvino P. Josol
Email: [email protected]
Phone: +63 906 0757721
Library Contact Brigida E. Bacani
Email: [email protected]
Phone: +63 951 3766681
7
Course Information – see/download course syllabus in the Black Board LMS
CC’s Voice: Good day, dear students! Welcome to this course EDP101/L: Computer
Fundamentals and Programming. Every time we introduce this
programming course to other engineering programs many would ponder
why they have this course included in the curriculum since you are
probably taking up Electrical, Mechanical, Chemical, or Civil Engineering.
Aside from the fact that this is a mandatory course, as stipulated in the
Commission on Higher Education Policies, Standards, and Guidelines
(CHED-PSG) for engineering programs, uilization and creation of new
technologies are highly essential in the fast-changing engineering world
that vastly dominated by IT, embedded systems, microelectronics, robotics,
and many more, which are computer-based. Moreover, as the world
preparing for the Fourth Industrial Revolution, future engineers must be
equipped with IT and programming skills. Under this subject, you are
expected to learn the necessary information technology concepts and
concepts of programming languages, use application software and the
Internet properly, use high-level programming languages by demonstrating
proficiency in algorithm development. And utilization of computer as a tool
in engineering practice.
Let us begin!
8
Big Picture
Week 1-3: Unit Learning Outcomes-UNIT 1 (ULO-1): At the end of the unit, you are
expected to:
Metalanguage
In this section, the most fundamental terms concerning basic computer study,
and to demonstrate ULO-1a will be reviewed to have uniform understanding in dealing
with the challenges that may be encountered in this course. You will encounter these
terms as we go through the study of the operations of the computer system. Please refer
to these definitions in case you will face difficulties in understanding the course.
9
4.1 Computer Hardware refers to the TANGIBLE materials in the
computer system and divided into five main categories namely:
4.1.2 Main Memory. Typically refers to the device that is used to retain
the information being processed. It generally is a metal-oxide-
semiconductor (MOS) where data is stored within MOS memory
cells on a silicon integrated chip. Main memory is a volatile type of
memory
Essential Knowledge
To perform the aforesaid big picture (unit learning outcomes) for the first three (3)
weeks of the course, you need to review basic knowledge in computer fundamentals
and computer programming principles that will be laid down in the succeeding pages.
Please note that you are not limited to exclusively refer to these resources. Thus, you
are expected to utilize other books, research articles and other resources that are
available in the university’s library e.g. ebrary, search.proquest.com etc.
11
In this generation, mainly batch processing operating system was used. Punch cards,
paper tape, and the magnetic tape were used as input and output devices. The
computers in this generation used machine code as the programming language.
The main features of the first generation are huge size devices, unreliable, supported
machine language only, very expensive, generated too much of heat, slow input, and
output devices, non-portable, consumed a lot of electricity.
Computers developed during the first generation were Electronic Numerical Integrator and
Computer (ENIAC) in 1945, Electronic Discrete Variable Automatic Computer EDVAC in
(1946), UNIVersal Automatic Computer (UNIVAC) in 1951, IBM 701 and IBM 650.
Figure2. UNIVAC(www.computerhistory.org)
12
Second Generation of Computer (1959-1965)
In this generation, transistors were used that were cheaper, consumed less power, more
compact, more reliable, and faster than the first-generation machines made of vacuum
tubes. In this generation, magnetic cores were used as the primary memory and magnetic
tape and magnetic disks as secondary storage devices. In this generation, assembly
language and high-level programming languages like FORTRAN, COBOL were used. The
computers used batch processing and multiprogramming operating system.
Compare to the previous generation, the main features of the second generation are the
invention of transistors the reduce the size of the machine. Second-generation computers
are more reliable in comparison to first-generation computers, generated less heat as
compared to first-generation computers, consumed less electricity as compared to first
generation computers. Faster data processing than first-generation computers and its
already supported with assembly languages.
Some computers of this generation were IBM 1620,IBM 7094,CDC 1604,CDC 3600,
UNIVAC 1108.
Compared to the prior generations, the third generation becomes advantageous with the
invention of the Integrated Circuit (IC), it becomes more reliable. Products were smaller in
terms of size, generated less heat, faster in terms of performance, lesser maintenance,
consumed lower electricity, and it supports high-level programming language.
13
This generation of computers became more powerful, compact, reliable, and affordable.
As a result, it gave rise to the Personal Computer (PC) revolution. In this generation,
timesharing, real-time networks, distributed operating system were used. All the high-level
languages like C, C++, DBASE, etc., were used in this generation.
Self-Help: You can also refer to the sources below to help you
further understand the lesson
[1] G. Bronson, C++ Programming principles and practices for scientists and engineers,
Boston: Cengage Learning, 2013.
[2] D. Malik, C++ Programming: from problem analysis to program design, Stamford:
Cengage Learning, 2015.
[3] J. Smith, C++ programs to accompany logic and design 8th edition, Boston: Cengage
Learning, 2015.
[4] D. Zak, An introduction to programming with C++ (8th Edition), Andover: Cengage
Learning, 2016.
[5] M. Main, Data structures and other objects using c++, Boston: Pearson, 2011.
Let’s Check
Activity 1: Minimum of 150 words, discuss your appreciation of the computer system.
14
Activity 2: Other than computer mouse and keyboard, make a list of input and output
devices that allow the computer to interact with. Describe each usage of every device.
Note: Upload .doc/docx file on the specified link.
Let’s Analyze!
1. What is the difference between System software and application software?
3. What probably is the main reason why the sizes of a computer significantly reduced
from the first generation to the recent?
5. In your recent and future challenges as an engineer, how computers and related
computer devices can help and achieve tasks?
In a Nutshell
We are now done with the review of the computer system, which we recall the
generations and history of the computer, parts of the computer systems, etc. Before
proceeding to the next unit, learning outcomes, be reminded of some essential points in
this section.
• The computer system is composed of two main parts the hardware and the software.
Hardware is the tangible materials in the computer system, while the computer
software is the computer program coded for the computer to perform its function.
Q&A List
If you have questions about computer system, kindly write down on the table provided.
Questions Answers
15
Big Picture in Focus:
ULO-1b. apply principles and concepts of different number systems
and its relations to computer system.
Metalanguage
In this section, the relationship of the different number systems and its functions
in digital computing will be discussed, and to demonstrate ULO-1b, this particular topic
will discuss the conversion of four different number systems (base2, base8, base10, and
base16) and its usage in the digital system.
Essential Knowledge
When we type some characters on the keyboard, the computer translates them in
numbers as computers can understand only numbers. When it is converted to numbers,
the microprocessor can easily manipulate further instruction on what to do to the
characters being coded. A computer can understand the positional number system where
there are only a few symbols called digits, and these symbols represent different values
depending on the position they occupy in the number.
Different number systems are used in the computer system. Example, for data
networking, IP address being assigned to each host addresses is represented in the
decimal number system of base10 (192.168.0.1) most probably for ease of recalling the
value since base 10 is the most common system. However, in actual principle in assigning
such address, it is being decoded in four octets of binary
numbers
(11000000.10101000.00000000.00000001). Now in modern network design, Internet
Protocol version 6 (IPv6) is being included, following the old model but it utilizes Base 16
number system.
16
The number system that we use in our day-to-day life is the decimal number system. The
decimal number system has a base of 10 as it uses 10 digits from 0 to 9. In the decimal
number system, the successive positions to the left of the decimal point represent units,
tens, hundreds, thousands, and so on.
Step 1: Divide the decimal number to be converted by the value of the new base.
Step 2: Get the remainder from Step 1 as the rightmost digit (least significant digit)
of the new base number.
Step 3: Divide the quotient of the previous divided by the new base.
Step 4: Record the remainder from Step 3 as the next digit (to the left) of the new
base number.
Repeat steps 3 and 4, getting remainders from right to left until the quotient becomes zero
in Step 3. The last remainder obtained, therefore, will be the Most Significant Digit (MSD)
of the new base number.
Example:
17
Step 2: Get the whole number part from Step 1 as the leftmost digit after the
decimal point of the new base number.
Step 3: Multiply the new fractional part from the previous multiplied by the new base.
Step 4: Record the whole number part of the result from Step 3 next to the digit of
the new base.
Repeat steps 3 and 4 until the fractional part becomes zero. Record the whole number
part taking the first answer to the new whole number as the first digit after the decimal
point.
Example:
Convert 0.62510 - > _____2
To convert from other base systems to the decimal system, the following steps may be
applied.
Step 1: Determine the column (positional) value of each digit (this depends on the
position of the digit and the base of the number system.
Step 2: Multiply the obtained column values (in Step 1) by the digits in the
corresponding columns.
Step 3: Sum the products calculated in Step 2. The total is the equivalent value in
decimal.
Example:
Convert 11101.012 ->________10
18
1 11101.012 (1 x 24) + (1 x 23) + (1 x 22) + (0 x 21) +
(1 x 20) + (1 x 2-1) + (1 x 2-2)
2 11101.012 16 + 8 + 4 + 0 + 1 + 0.0 + 0.25
3 11101.012 29.2510
Table 3 Binary to Decimal Conversion
To convert from binary to hexadecimal or octal, the following theorem may be applied:
R1 = 8 (base – 8) octal R1 = 16 (base – 16) hexadecimal
R2 = 2 (base – 2 ) binary R2 = 2 (base – 2 ) binary
R1 = R2D R1 = R2D
8 = 23 16 = 24
Therefore:
3 digits in base-2 (binary) is equivalent to 1 digit in base – 8 (octal)
Ι 001 Ι Ι 010 Ι
(0x22 + 0x21 + 1x20)8 (0x22 + 1x21 + 0x20 )8
(0+0+1)8 (0+2+0)8
Step 1. Group the given binary number to 4 bits starting from the Least Significant
Bit(LSB) or the rightmost side of the number. If the remaining binary number is
less than 4 digit, ADD zero (0) to the right significant bit to make it 4 bits.
Given Group/s
10102 = Ι 1010 Ι
Step 2. Compute each group individually following the process in example 1.
Ι 1010 Ι
(1x03 + 0x22 + 0x21 + 1x20)16
20
Octal number system uses eight digits, 0,1,2,3,4,5,6,7 that’s why it’s called base 8
number system. The first position in an octal number represents a 0 power of the base (8).
The last position in an octal number represents a x power of the base (8). Example 8x
where x represents the last position - 1
18 = 0012
28 = 0102
38 = 0112
18 = 0012
28 = 0102
38 = 0112
Step 2. Gather all the result for the binary
21
= Ι0 Ι 5 Ι 3 Ι
Example 1: Find the equivalent decimal number of the Hexadecimal number 10A16.
Example 2: Find the equivalent binary number of the Hexadecimal number 10A16.
Step 1. Get the 4bits equivalent of each given hexadecimal number.
116 = 00012
016 = 00002
A16 = 10102
Step 2. Arrange the results same as how given was being arrange to get the
answer.
Answer : 10A16 = 0001000010102
Example 3: Find the equivalent octal number of the Hexadecimal number ABC16.
22
Step 1. Get the 4-bits equivalent of each given hexadecimal number.
A16 = 10102
B16 = 10112
C16 = 11002
Step 2. Arrange the results the same as how given to get the binary equivalent.
ABC16 = 1010101111002
Step 3. Group the binary equivalent into 3bits starting for the LSB, then arrange it
to get the result.
Given Group/s
Self-Help: You can also refer to the sources below to help you
further understand the lesson
[1] G. Bronson, C++ Programming principles and practices for scientists and engineers,
Boston: Cengage Learning, 2013.
[2] D. Malik, C++ Programming: from problem analysis to program design, Stamford:
Cengage Learning, 2015.
[3] J. Smith, C++ programs to accompany logic and design 8th edition, Boston: Cengage
Learning, 2015.
[4] D. Zak, An introduction to programming with C++ (8th Edition), Andover: Cengage
Learning, 2016.
[5] M. Main, Data structures and other objects using c++, Boston: Pearson, 2011.
Let’s check
23
Convert the given values based on the required number system.
In a Nutshell
We are now done with the four different number systems, namely binary, octal, decimal,
and hexadecimal number systems. Before proceeding to the next unit, be reminded of
some essential points in this section.
• The binary number system is the base2 system that represents a value using only two
digits (0,1). This number system is commonly associated with the principle of electricity
that has two states: (logic 1 or ON and logic 0 or OFF).
• The octal number system is the base8 number system that represents a specific value
using eight digits (0-7).
• The decimal number system is the universal number system. Uses ten different digits
(09) to represent a value.
• Hexadecimal number system is base16 number system that represent a value using 16
digits (0-9, A, B, C, D, E, F).
Q&A List
If you have any questions regarding number systems, kindly write down on the table provided.
Questions Answers
24
Big Picture in Focus:
ULO-1c: Understand computer programming principles and apply tools in
Developing program logic.
Metalanguage
At the end of this unit, you are expected to understand the importance of algorithm,
pseudocode, and flowchart in computer programming. Also, you are expected to design
your algorithm, pseudocode, and flowchart based on the given situation and criteria.
Essential Knowledge
The algorithm is a step by step method of solving a problem. It is commonly used
for data processing, calculation, and other related computer and mathematical operations.
An algorithm is also used to manipulate data in various ways, such as inserting a new data
item, searching for a particular topic, or sorting an item.
Sample Algorithm:
Example 1: The algorithm in finding the perimeter and area of a rectangle is
1. Get the length of the rectangle.
2. Get the width of the rectangle.
3. Find the perimeter using the following equation: Perimeter =2*(length + width) 4.
4. Find the area using the following equation: Area = length * width
25
5. Display results.
Example 2: An algorithm to find the largest among three different numbers entered by the
user.
Pseudocode is an informal program description that does not contain code syntax or
underlying technology considerations. It summarizes the program flow but excludes
underlying programming details. Often at times, algorithms are represented with the help
of pseudo codes as they can be interpreted by programmers no matter what their
programming background or knowledge is. Pseudo code, as the name suggests, is a false
code or a representation of code which can be understood by even a layman with some
school level programming knowledge.
Example 1: A pseudocode on finding the area and perimeter of a rectangle.
26
Begin
input length, width
perimeter = 2 * (length + width) area
= length * width
print perimeter
print area
End
Begin
Initialize counter to 0
Initialize accumulator to 0
Loop
Read input from keyboard
Accumulate the input
Increment the counter
While counter is less than 10
Calculate average
Print sum
Print average
End
Begin
Declare an integer variable called n
Declare an integer variable sum
Declare an integer variable
f1 Declare an integer variable f2
set sum to 0 set f1 and f2 to 1 set n
to 50 repeat n times sum = f1 + f2
f2 = f1 f1 = sum print sum end loop
End
27
Flowchart Symbol Meaning
Terminal
Input/output operation
Process
Initialization
Pre-defined process
Off-page connector
On page connector
28
Decision
Flow lines
Operator Description
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
Table 8. Relational Operators
Operator Description
! not
&& and
|| Or
Table 9. Logical Operators
29
Pseudocode Flowchart
Begin
initialize x and y input
x and y sum
= x+y
print sum
End
30
Pseudocode Flowchart
31
Begin
input select
if select == 1
print Balance Inquiry”
goto a
if select == 2
print withdrawal”
goto b
if select == 3
print Exit”
goto c
End
Pseudocode Flowchart
32
Begin
i=0 sum = 0 while i<10
input x sum
= sum +x
++i avg =
sum / 10 print
avg
End
Self-Help: You can also refer to the sources below to help you
further understand the lesson
[1] G. Bronson, C++ Programming Principles and practices for scientists and engineers,
Boston: Cengage Learning, 2013.
[2] D. Malik, C++ Programming: from problem analysis to program design, Stamford:
Cengage Learning, 2015.
[3] J. Smith, C++ programs to accompany logic and design 8th edition, Boston: Cengage
Learning, 2015.
[4] D. Zak, An introduction to programming with C++ (8th Edition), Andover: Cengage
Learning, 2016.
[5] M. Main, Data structures and other objects using C++, Boston: Pearson, 2011.
Let’s check!
33
ULO-1c: Task 1
Given below is the pseudocode on how to compute the overtime pay of the employee.
ULO-1c: Task 2
2. How many decision boxes are needed in implementing the flowchart based on the
given pseudocode?
3. List all symbols used in creating the flowchart of the given pseudocode.
ULO-1c: Task 3
Create pseudocode and flowchart that will accept the evaluation score of a faculty and
determine its equivalent remarks. Remarks are based on the following criteria:
4.50 – 5.00 - Outstanding
4.00 – 4.49 - Very Satisfactory
3.50 – 3.99 - Satisfactory
3.00 – 3.49 - Needs Improvement
2.99 below - Poor
Algorithm:
34
The algorithm to determine the equivalent remarks of a faculty’s evaluation score is:
1. Get the name of the faculty.
2. Get the evaluation score of the faculty.
3. Test the score if it is greater than or equal to 4.50.
4. If the score is greater than or equal to 4.50, remarks are “Outstanding”. However,
if the score is less than 4.50, proceed to step 5.
5. Test the score if it is greater than or equal to 4.00.
6. If the score is greater than or equal to 4.00, remarks are “Very Satisfactory”.
However, if the score is less than 4.00, proceed to step 7.
7. Test the score if it is greater than or equal to 3.50.
8. If the score is greater than or equal to 3.50, remarks are “Satisfactory”. However, if
the score is less than 3.50, proceed to step 9.
9. Test the score if it is greater than or equal to 3.00.
10. If the score is greater than or equal to 3.00, remarks are “Needs Improvement”.
However, if the score is less than 3.00, remarks are” Poor”.
11. Display the faculty name, evaluation score, and remarks.
In a Nutshell
We are now done discussing the basic requirement prior using symbols and techniques in
designing a simple program. We discuss the purpose and importance of having an
algorithm, flowchart, and pseudocode in computer programming. Before proceeding to the
next unit, learning outcomes, be reminded of some essential points in this section.
• The algorithm is the step-by-step procedure on how the desired program will execute.
• A flowchart is a step-by-step procedure in designing a computer program; however, it's
being represented with symbols.
• Pseudocode is an informal program description that does not contain code syntax or
underlying technology considerations.
35
Q&A List
If you have any questions, write on the blank below.
Questions Answers
36
Big Picture
Week 4-6: Unit Learning Outcomes – Unit 2 (ULO-2): At the end of the unit you are
expected to:
a. Understand and apply data types, operators, input/output programs and
hierarchies
of computer programming.
b. Apply logic program control structures using sequence and selection/decision
c. Apply knowledge in program recursion structures such as while loop, do/while
loop
and for loop.
Metalanguage
In the previous section, we discussed programming model tools such as flowchart,
algorithm and pseudocode to make the program more scientific, structure and easy to
troubleshoot. Now, we will start discussing the common terminologies and principles in
computer programming for us to be ready for actual laboratory work.
Also, at the conclusion of this section, you would be able to learn to manipulate
numeric data using arithmetic operations, learn how to use predefined functions to
determine the six (6) trigonometric functions of an angle shown both in degrees and
radians, apply basic math and trigonometric functions to solve for unknown angles of Case
4 Oblique Triangle using Cosine Law and Angle Sum Formula and apply manipulators to
properly format outputs.
Definition of Terms
1. Keywords. This is also known as reserved words that have special meaning in
DevC++. Keywords cannot be used for another purpose/s and lastly written in
lowercase.
37
2. Programmer-Defined Identifiers Names made up or customized by the programmer.
Commonly it’s called variable, this is used to represent various things in programming
especially memory locations.
Example: int var1; (var1 is the variable)
3. Operators: Used to perform operation on data like arithmetic operators (+, -, *, %) and
assignment (=).
Example: num3 = num1 + num2 (= and + are the operators)
4. Punctuation: Characters that mark the end of a statement, or that separate items in a
list
Example: double num1 = 5, x, sum; (, and ; are the punctuations)
5. Line: In a source file, a line is all of the characters entered before a carriage return.
Blank lines improve the readability of a program.
Example: Sample below is a four sample lines; line 3 is a blank line.
10. Linker: A program that links separately compiled function together into one program. It
combines the functions in the standard C library with the code that you wrote. The
output of the linker is an executable program.
38
11. Library: The file containing the standard functions that can be used by your program.
These functions include all I/O operations as well as other useful routines.
12. Compile time. The events that occur while your program is being compiled. A
common occurrence during compile time is a syntax error.
13. Run time. The events that occur while your program is executing.
14. Input, Processing and Output: Three steps that many programs perform
1. Gather input data (from keyboard, from files on disk drives).
2. Process the input data.
3. Display the results as output (send it to the screen or printer, write it to a file)
Programming Process: Before start creating a program, better understand the given
process below.
(a) Define what the program is to do.
(b) Visualize the program running on the computer
(c) Use design tools to create a model of the program such as (algorithms, flowchart,
pseudocode, etc.) (d) Check the model for logical errors.
(e) Write the program source code.
(f) Compile the source code.
(g) Correct any errors found during compilation.
(h) Link the program to create an executable file.
(i) Run the program using test data for input
(j) Correct any errors found while running the program
(k) Validate the results of the program. If error/s found go back to first step.
Essential Knowledge
Data Types
There are five elementary data types in C: character, integer, floating point, double
floating point, and void. Values of type char are used to hold ASCII characters or any 8-bit
quantity. Variables of type int are used to hold integer quantities. Variables of type float
and double are used to hold real numbers.
The sizes are shown below:
Type Bit Width Range
char 8 0 to 255
39
int 16 -32768 to 32767
float 32 3.4e-38 to 3.4e+38
double 64 1.7e-308 to 1.7e+308
void 0 valueless
Declaration of Variables
All Variables must be declared before they are used. The general form of a declaration is
shown here:
type variable_list;
Here, type must be a valid C data type and variable-list may consist of one or more
identifier names with comma separators.
Example:
char gender; int x, y,
z; float amount, interest;
double balance, profit, loss;
Assignment Statements
The general form of the assignment statement is
variable_name = expression;
Where an expression may be as simple as a single constant or as complex as a combination
of variables, operators, and constants. The left part of the assignment must be a variables,
not a function or a constant.
Arithmetic Operators
Operator Meaning Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus division x%y
-- Decrement x--
++ Increment x++
Table 10. Mathematical Operators
40
Increment and Decrement
C allows two very useful operators. These are the increment and decrement operators,
++ and --. The operation ++ adds 1 to its operand, and – subtracts 1. See illustration
below:
x = x + 1;
Is the same as
++x;
Also; x
= x – 1;
Is the same as
--x;
Both the increment and decrement operators may neither precede or follow the operand.
For example, x = x + 1; can be written
++x;
or x++;
However; there is a difference when they are used in an expression. When an increment or
decrement operator precedes its operand, C performs the increment or decrement
operation prior to using the operand’s value. If the operator follows its operand, C uses the
operand’s value before incrementing or decrementing it. Consider the following:
x = 25;
y = ++x;
In this case, y is set to 26. However, if the code had been written as x = 25; y=
x++; y would have been set to 25. In both cases, x is set to 25; the difference is when it
happens. There are significant advantages in being able to control when the increment or
decrement operation takes place.
Programming Process
41
A program performs three basic operations: it gets data, it manipulates the data, and it
outputs the results. From prior activity, the three basic elements mentioned above were
made known using an algorithm, flowchart, and pseudocode. In any standard system
development, source code always comes after the preliminary conceptualization. On this
laboratory, the basic concept of input, process and output (IPO) will be shown by the use
of pre-defined input and output statements as well as basic mathematical and
trigonometric functions.
Moreover, to properly display results, various output functions and manipulators are
available under the #iomanip header file. Manipulators are necessary to properly display
floating-point numbers, align numbers in specific columns or fill the empty spaces between
strings and numbers.
Shown in table 10 and 11 are the mathematical functions and operators in Dev C++,
and in table 3.3 are the functions you may use to properly format and manipulate floating
point values.
42
atan(x) arctan of x atan(60) cmath/Math.h
1 #include<iostream>
2 #include<math.h>
3 using namespace std;
4
5 double x, y; // variables
6 int main()
43
7 {
8 cout << "Enter value for x : ";
9 cin >> x;
10 y = pow(x,4)-(5*pow(x,3))+(3*pow(x,2))-(2*x);
11 cout << "\nThe value of y is : "<< y;
12 return 0;
13 }
Questions:
ULO(2-a) Task B
Develop a program that will solve trigonometric values and make use of cosine law and
Angle Sum Formula.
1. Create a program that will solve for the unknown parts of an Oblique Triangle (Case
4: Given three sides).
a. The program will ask for the values of sides a, b, and c.
b. The program will then display the unknown angles; alpha, beta and gamma.
c. Lastly, it will show the result of Mollweide’s Equation
See the
figure below to visualize the screen display.
Oblique Triangle
Case 4: Given three sides (by Cosine Law)
Input sides a : ______ b: ______ c: ______
<Press Any Key to solve for unknown angles> Alpha: _______
Beta:______ Gamma:_______
Questions:
1. What is the preprocessor of the cosine function? Syntax of cosine function?
2. How do you control the number of floating-point values?
3. What will be the result for Mollweide’s Equation if the entered values for sides a, b,
and c are 30.3, 40.4, and 62.6, respectively in ULO(a) Task 2.2?
4. What is the C program function for square root?
5. What is the syntax for determining angle alpha, beta and gamma in the program?
Q&A List
Please write your Questions on the table below.
Questions Answers
Metalanguage
45
At the conclusion of this section, you should be able to use the basic mathematical
operation to compute for grades. use if…else conditional structure in determining
appropriate grade remarks, use appropriate logical and relational operators to cover the
desired range of grades, apply mathematical concepts to solve geometric figures, use
both numeric and character case label for the switch structure and lastly use switch
structure as a selection structure both for main and sub menu.
Essential Knowledge
The conditional statement is a programming language statement that decides an
execution path based on whether some condition is evaluated to true or false or by simply
making a choice.
In C++, there are two selections or branch control structures: if statements and the
switch structure. For the if…else structure, statements can be used to create a one-way
selection, two-way selection, and multiple selections. On the other hand, a switch
structure is usually used in a menu-driven program.
Relational Operators
Relational operators are used when dealing with the comparison of numeric and
character values. Shown in Table 13 are the different symbols and descriptions of each
relational operator.
Symbol Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
Table 13. Relational Operators
46
In evaluating an expression with multiple relational operators, a hierarchy of
relational operators is being used. Refer to Table 4.2 for the hierarchy of relational
operators.
An expression of the form (num1 > num2) is called a relational expression. Note
that it does not assert that num1 is greater than num2. It actually tests to see if this is true.
Therefore, relational expressions are Boolean. Their value must be either true or false.
One-way Selection
Syntax:
if (expression)
statement;
#include <iostream>
using namespace std;
int main()
{
float average;
cout << "Input your average" << endl; cin
>> average; if (average >= 60) // note the use of a relational
operator cout
<< "You Pass" << endl;
if (average > 95) cout <<
47
"A+" << endl; return
0;
}
In the example code above, if the input average is 90 then only the first condition is
true and executed. If the input average is less than 60, say 50, then none of the conditions
are true and executed. An average of 97 in this case will allow the two conditions to be
evaluated true and executed. Therefore, a trailing if statement could result to the
following: only one condition is being executed, all condition is being executed, and no
condition is being executed.
Two-way Selection
Syntax:
if (expression)
statement; else
statement;
There are many programming situations in which you must choose between two
alternatives. To choose between two alternatives, C++ provides the if…else statement.
Unlike in Sample Program Condition A, where there are different scenarios in evaluation,
the if…else statement will allow only one condition to be true and executed. Example
enhancement to Sample Program Condition A is shown below:
In every if/else statement, the program can take only one of two possible paths. Multiple
statements can be handled using curly braces in the same way as the if statement.
Syntax:
if (condition1)
48
{
statement/s;
}
else if (condition2)
{
statement/s;
}
else if (condition3)
{
statement/s;
}
else
{
statement/s;
}
Some problems require the implementation of more than two alternatives, for that you
would need multiple selection paths.
Suppose we need to decide what kind of vacation to take based on a yearly work bonus:
= if the bonus is less than $1,000 we set up a tent and eat
steak in the back yard
= if the bonus is less than $10,000 and greater than or equal to
$1,000 we go to Disney World = if the bonus is $10,000
we go to Hawaii
We could code this using if/else if/else statement as follows:
if (bonus < 1000) cout << "Another vacation on the
lawn" << endl;
else if (bonus < 10000) cout << "Off to
Disney World!" << endl; else if
(bonus == 10000) cout << "Lets go to
Hawaii!" << endl;
else
{
cout << bonus << " is not a valid bonus" << endl; cout
<< "Please run the program again with valid data"
49
<< endl;
} // Note the necessary use of the curly brackets here
Logical Operators
By using relational operators, C++ programmers can create relational expressions. It is
also possible to combine truth values into a single expression by using logical operators.
The syntax used by C++ for logical operators is the following:
Operator Description
&& AND
|| OR
! NOT
Table 15. Logical Operators
The NOT operator negates a single statement. For example, “it is sunny” can be
negated by “it is not sunny.” Other logical operators are the OR and the AND, which
evaluates two or more statements. The OR and AND logical operators allow the creation
of a relational expression from two or more relational expressions.
Consider x = 15, y = 7, and z= -5 for the example shown in the table below:
Expression Evaluation
(x > y) && (y > z) TRUE
(x > z) && (z > y) FALSE
(x <= z) || (y == z) FALSE
(x <= z) || (y != x) TRUE
!(x >= y) FALSE
Table 16. Evaluation of Logical Operators
Let us now apply the logical operators in the following statement:
An individual is allowed to vote if he is of legal age, that is, if he is 18 yrs old and above,
and has resided for at least 6 months. Take note of the conjunction and; it means both
statements must be true before an individual be allowed to vote.
Let (age >= 18 yrs) be statement A and (residency >= 6 months) be statement B.
Both statements must be true, that means you must be at least 18 years old and has
resided in the locality for at least 6 months in order for you to vote. In C++, the correct
syntax would be:
Previous exercises deal with control structures that process computer program by
making the selection. Both exercises show how to allow a program to alter the sequential
flow of execution. The if/else if structure which was presented on previously is one of the
selection structures supported by C++, the second one is the switch structure on which it
does not require the evaluation of a logical expression.
C++’s switch structure gives the computer the power to choose from among many
alternatives.
Syntax:
switch(expression)
{ case
value1:
statements1;
break;
case value2:
statements2;
break;
.
. case
valuen:
statementsn;
break;
default:
statements; } // end of
switch structure
1. When the value of the expression is matched against a case value (also called
a label), the statements execute until either a break statement is found or the
end of the switch structure is reached.
2. If the value of the expression does not match any of the case values, the
statements following the default label execute. If the switch structure has no
default label, and if the value of the expression does not match any of the case
values, the entire switch statements are skipped.
3. A break statement causes an immediate exit from the switch structure.
51
// This program illustrates the use of the switch statement.
#include <iostream>
using namespace std;
int main()
{
char grade;
Self-Help: You can also refer to the sources below to help you
further understand the lesson
[1] G. Bronson, C++ Programming: principles and practices for scientists and engineers,
Boston: Cengage Learning, 2013.
[2] D. Malik, C++ Programming: from problem analysis to program design, Stamford:
Cengage Learning, 2015.
52
[3] J. Smith, C++ programs to accompany logic and design 8th edition, Boston: Cengage
Learning, 2015.
[4] D. Zak, An introduction to programming with C++ (8th Edition), Andover: Cengage
Learning, 2016.
[5] M. Main, Data structures and other objects using c++, Boston: Pearson, 2011.
Weights Assignment
54
ULO(2-b) Task B: Conditional Statement (switch…case)
Develop a program that will solve the area, surface area and perimeter of geometric
figures (see table 17). Use on switch structure for conditional statements.
Perimeter Square P = 4a
Rectangle P = 2(l + b)
Area Triangle A = b*h / 2
Trapezoid A = ½ (b1 + b2) h
Circle A = πr2
Surface Area Cube S = 6a2
Cylinder S = 2πr2 + 2πrh
Sphere S = 4πr2
Table 17. Formulae of Different Geometric Figures
Program Requirements
1. Shown in figure 5.1 is the main screen of the program where it allows the user to
either choose to solve for area, surface area, perimeter or volume.
2. After selection, the sub-menu will appear prompting the user to select what figure
to solve with.
3. After this, the required inputs are keyed in like radius, length, base or height
whichever is applicable.
4. The answer to a particular solution will be shown, and the user will be prompted to
go back to the sub-menu. The user can now either chose another figure to solve or
go back to the main menu (please see figures 8-10).
5. Use solely switch structure for all parts of the program, which requires the selection
process.
[A] Perimeter
[B] Area
[C] Surface Area
[D] Exit
Enter Option: ____A_____
55
Perimeter
Geometric Figure
1] Square
2] Rectangle
Square
Enter side measurement of the square: 4.25 inches
of 4.25 inches
is _17.00 inches
56
In a Nutshell
In C++, there are two selections or branch of control structures: if else statements
and the switch structure. For the if…else structure, statements can be used to create a
one-way selection, two-way selection, and multiple or nested selections. On the other
hand, a switch structure is usually used in a menu-driven program.
Q&A List
Please write your queries on the table provided below:
Questions Answers
Ratings
Parameters
3 2 1
Source code contains no Source code contains Source code contains
Syntax syntax error. 1 to 5 syntax errors. more than 5 syntax
(30%) (30) (20) errors.(10)
57
Source code contains the Source code lacks Source code is not
Specifications complete details to run necessary details to enough to run the
(30%) the program correctly. run the program program correctly.
(30) correctly.(20) (10)
Source code is well Minor issues such as Major issues are
Readability organized and easy to variable naming, causing the codes to
(10%) understand. variable utilization, be not readable.
(10) etc. are observed. (6) (3)
Source code is well Source code allows Source code does not
Screen Output organized and easy to the required screen meet the required
(10%) understand. output to be displayed screen output to be
correctly with 1-3 displayed correctly.
(10) errors found.(6) (3)
The documentation is The documentation The documentation
well written and lacks some didn’t satisfy all the
Documentation clearly explained all information and some questions that were
(20%) the mistakes are found in given in the laboratory
questions given in the the questions. exercise.
laboratory exercise. (14) (7)
(20)
58
Metalanguage
At the conclusion of this section, you should be able to understand and apply the concept
of repetitive execution and differentiate and apply looping structures; while, do/while and
for loop.
Essential Knowledge
In computer programming, a loop is called iteration or repetition and is being
implemented by the use of control structures. It is referred to as a sequence of instructions
that is continually repeated until a certain condition is satisfied.
Iterative statements have three important parts, such as initialization, condition and
updater. These three parameters must be configured properly in order to achieve the
desired iteration.
There are three types of loop: while, do-while and for a loop.
The while loop statement allows the programmer to specify that a program should repeat
an action while some condition remains true. The program tests the loop-continuation
condition at the beginning of the loop before executing the rest of the loop's body. If the
condition is false, the loop never executes.
Syntax:
initialization;
while
(condition) {
statements;
updater;
}
Syntax:
initialization;
do
{
statements;
updater;
} while (condition);
The body of the do...while statement should always be enclosed within braces to avoid
confusion with the while statement.
Repetition structures, or loops in while loop format generally come in two forms. The two
loops are:
60
will be executed. It is a repetition procedure for solving a problem by using a
sentinel value (also called a signal value, a dummy value, or a flag value) to
indicate "end of data entry."
Self-Help: You can also refer to the sources below to help you
further understand the lesson
[1] G. Bronson, C++ Programming:principles and practices for scientists and engineers,
Boston: Cengage Learning, 2013.
[2] D. Malik, C++ Programming: from problem analysis to program design, Stamford:
Cengage Learning, 2015.
[3] J. Smith, C++ programs to accompany logic and design 8th edition, Boston: Cengage
Learning, 2015.
[4] D. Zak, An introduction to programming with C++ (8th Edition), Andover: Cengage
Learning, 2016.
[5] M. Main, Data structures and other objects using c++, Boston: Pearson, 2011.
In a Nutshell
Looping is referred to as a sequence of instructions that is continually repeated until a
certain condition is satisfied. There are 3 forms of looping; for loop and while loop which
are both pre-test loop; and do-while loop which is a post-test loop. If the program can
determine in advance, the number of repetitions needed, the for loop is the correct choice.
If you do not know, and the program cannot determine in advance the number of
repetitions needed, and it could be none, while loop is the right choice. If you do not know,
and the program cannot determine in advance the number of repetitions needed, and it is
at least 1, the do/while is the right choice.
Let’s check and Analyze!
61
#include <iostream>
using namespace std;
int main()
{ char letter =
'a';
return 0;
}
#include <iostream>
using namespace std;
int main()
{
// Fill in the code to define and initialize to 1 the variable month float
total = 0, rain;
cout << "Enter the total rainfall for month "
<< month << endl;
cout << "Enter -1 when you are finished" << endl;
{
// Fill in the code to update total by adding it to rain cout
<< "Enter the total rainfall in inches for month "
<< month << endl;
cout << "Enter -1 when you are finished" << endl;
if (month == 1)
cout << "No data has been entered" << endl;
else
cout << "The total rainfall for the " << month-1
<< " months is "<< total << " inches." << endl;
return 0;
}
1. Run the program several times with various input. Record your results. Are they
correct?
2. What happens if you enter –1 first?
3. What happens if you enter only values of 0 for one or more months?
4. Is there any numerical data that you should not enter?
// This program displays a hot beverage menu and prompts the user to
// make a selection. A switch statement determines
// which item the user has chosen. A do-while loop repeats until
// the user selects item E from the menu.
#include <iostream>
#include <iomanip>
using namespace std;
63
int main()
{
// Fill in the code to define an integer variable called
// number, a floating point variable called cost,
// and a character variable called beverage
bool validBeverage;
cout << fixed << showpoint << setprecision(2);
do
{
cout << endl << endl; cout << "Hot Beverage Menu"
<< endl<< endl; cout << "A: Coffee $1.00" <<
endl; cout<< "B: Tea $ .75"<<endl; cout << "C: Hot
Chocolate $1.25" << endl; cout << "D: Cappuccino
$2.50" << endl << endl << endl; cout << "Enter the
beverage A,B,C, or D you desire"
<< endl; cout << "Enter E to exit the program"
<< endl << endl;
switch(beverage)
{ case 'a':
case 'A':
case 'b':
case 'B':
case 'c': case
'C': case 'd':
case 'D':
default:
validBeverage = true;
break;
validBeverage = false;
} if
(validBeverage == true)
{
cout << "How many cups would you like?" << endl; //
Fill in the code to read in number
}
64
// Fill in the code to begin a switch statement
// that is controlled by beverage
{
case 'a': case
'A':
cost = number * 1.0;
cout << "The total cost is $ " << cost << endl;
break;
// Fill in the code to give the case for hot chocolate ($1.25 a cup)
// Fill in the code to give the case for tea ($0.75 a cup)
// Fill in the code to give the case for cappuccino ($2.50 a cup)
case 'e':
case 'E': cout << " Please come again" << endl;
break;
default:
cout << // Fill in the code to write a message
// indicating an invalid selection.
cout << " Try again please" << endl; }
} // Fill in the code to finish the do-while statement with the
// condition that beverage does not equal E or e.
// Fill in the appropriate return statement
}
65
// This program has the user input a number n and then finds the //
mean of the first n positive integers.
#include <iostream>
using namespace std;
int main()
{
int value; // value is some positive number n
int total = 0; // total holds the sum of the first n
//positive numbers
int number; // the amount of numbers float mean;
// the average of the first n positive
// numbers
cout << "Please enter a positive integer" << endl;
cin >> value;
if (value > 0)
{
for (number = 1; number <= value; number++)
{
total = total + number;
}
mean = static_cast<float>(total) / value; //
note the use of the typecast operator here cout
<< "The mean average of the first " << value
<< " positive integers is " << mean << endl;
}
else cout << "Invalid input - integer must be positive"
<< endl; return
0;
}
66
2. What happens if you enter a float such as 4.58 instead of an integer for value? Try
it and record the results.
#include <iostream>
using namespace std;
int main()
{
int numStudents;
float numHours, total, average; int student, day = 0;
// these are the counters for the loops
cout << "This program will find the average number of”
<<” hours a day that a student spent programming”
<<” over a long weekend\n\n"; cout
<< "How many students are there? ";
cin >> numStudents;
67
<< ”day spent programming by "
<< "student " << student << " is " << average
<< endl << endl << endl;
} // end of outer loop return
0;
}
Sample Run:
This program will find the average number of hours a day that a student spent
programming over a long weekend
Note that the inner loop of this program is always executed exactly three times— once for
each day of the long weekend. Which part of the code you need to alter so that the inner
loop iterates n times, where n is a positive integer input by the user. In other words, let the
user decide how many days to consider just as they choose how many students to
consider.
Problem 1:
68
Write a program that performs a survey tally on beverages. The program should prompt
for the next person until a sentinel value of -1 is entered to terminate the program. Each
person participating in the survey should choose their favorite beverage from the following
list:
1. Coffee 2. Green Tea 3. Soda 4. Juice
Sample Run:
****************************************************
****************************************************
Please input the favorite beverage of person #1:
****************************************************
**************************************************** Please
input the favorite beverage of person #2:
****************************************************
**************************************************** Please
input the favorite beverage of person #3:
****************************************************
****************************************************
Please input the favorite beverage of person #4:
69
****************************************************
**************************************************** Please
input the favorite beverage of person #6:
====================================================
====================================================
The total number of people surveyed is 5.
The results are as follows:
====================================================
====================================================
Problem 2:
Suppose Dave drops a watermelon off a high bridge and lets it fall until it hits the
water. If we neglect air resistance, then the distance d in meters fallen by the watermelon
after t seconds is d = 0.5 * g * t2, where the acceleration of gravity g = 9.8 meters/second2.
Write a program that asks the user to input the number of seconds that the watermelon
falls and the height h of the bridge above the water. The program should then calculate
the distance fallen for each second from t = 0 until the value of t input by the user. If the
total distance fallen is greater than the height of the bridge, then the program should tell
the user that the distance fallen is not valid. Sample Run 1:
70
2 19.6
Sample Run 2:
Ratings
Parameters
3 2 1
Source code contains no Source code contains Source code contains
Syntax syntax error. 1 to 5 syntax errors. more than 5 syntax
(30%) (30) (20) errors.(10)
71
Source code contains the Source code lacks Source code is not
Specifications complete details to run necessary details to enough to run the
(30%) the program correctly. run the program program correctly.
(30) correctly.(20) (10)
Source code is well Minor issues such as Major issues are
Readability organized and easy to variable naming, causing the codes to
(10%) understand. variable utilization, be not readable.
(10) etc. are observed. (6) (3)
Source code is well Source code allows Source code does not
Screen Output organized and easy to the required screen meet the required
(10%) understand. output to be displayed screen output to be
correctly with 1-3 displayed correctly.
(10) errors found.(6) (3)
The documentation is The documentation The documentation
well written and lacks some didn’t satisfy all the
Documentation clearly explained all information and some questions that were
(20%) the mistakes are found in given in the laboratory
questions given in the the questions. exercise.
laboratory exercise. (14) (7)
(20)
Big Picture
Week 7-9: Unit Learning Outcomes-Unit 3 (ULO-3): At the end of the unit, you are expected
to:
a. Create and invoke program-defined void and return-type functions
b. Create a program using single-dimension array
c. Create a program using multi-dimensional arrays of numeric and characters
72
Big Picture in Focus:
ULO 3-a. Be able to create and invoke program-defined void and return-type
functions
Metalanguage
This section will serve as your guide on understanding programming functions better
and to be able to demonstrate ULO 3-a, we will be discussing methods in creating program-
defined function of a particular task, void type and create a program-defined function of a
particular task, return type.
Essential Knowledge
A function is a block of code that performs a specific task. Every C++ program contains at
least one function, which is named main(). However, most C++ programs contain many
functions. Some of this functions are built into the C++ language. If for example the function
pow (base, exp) and sqrt() are to be used, you must include the header file that contains the
function’s specification via the include statement, which is in this case #include<cmath>.
In the previous exercises, you use only the function main(); the programming
instructions are packed into one function. This technique, however, is good only for short
programs. For large programs, it is not practical to put the entire programming instructions
into one function. You must learn to break the problem into manageable pieces. This
laboratory exercise will demonstrate the use of programmer-defined function. Using functions
may it be pre-defined or programmer define is another way of processing a computer
program, you may use such method to work with the other control structures that were
introduced in the previous exercises.
Other program functions, like main(), are created by the programmer. These functions are
often referred to as program-defined functions because the function definitions are
contained in the program itself rather than in a different file. But why would a programmer
need more than the main function? One reason is to avoid duplication of code. If the same
task needs to be performed in more than one section of a program, it is more efficient for the
programmer to enter the code once, in a function. Any section in the program can then call
the function to perform the required task.
73
Program-defined functions also allow large and complex programs to be broken into small and
manageable tasks. Other advantages:
• It allows you to focus on just that part of the program and construct it.
• Different people can work on different functions simultaneously.
• If a function is needed in more than one place in a program or in different programs, you
can write it once and use it many times.
• Using functions greatly enhances the program’s readability because it reduces the
complexity of the function main.
All value-returning functions, whether built-in or program-defined, perform a task and then
return precisely one value after the task is completed.
74
Consider the following statements:
double a = 13.00;
double b = 36.53;
The expression larger(a, b) is a function call. Here, a and b are the actual parameters.
When the expression larger(a, b) executes, the value of a is copied into x, and the value of b
is copied into y. Therefore the statement larger(a, b) outputs the larger of a and b.
Encode the program below and observe how the function larger() works.
//This program finds the largest number of a set of 10 numbers
int main()
{
double num; //variable to hold the current number
double max; //variable to hold the larger number
int count; // loop control variable
75
cout << “Enter 10 numbers.” << endl;
cin >> num;
max = num;
return 0;
} // end main
Void functions and value-returning functions have similar structures. Both have a
heading and a body. Both can be placed either before or after the function main. However;
void functions do not have a data type. Therefore, return statement and return function type
of the void functions are meaningless. Return statement can still be used without any value; it
is typically used to exit the function early. A call to a void function is a stand-alone statement.
Therefore, to call a void function, you use the function name together with the actual
parameters, if any, in a stand-alone statement.
76
}
1. Value parameter (pass by value): A formal parameter that received a copy of the
content of the corresponding actual parameter.
2. Reference parameter (pass by reference): A formal parameter that receives the
location (memory address) of the corresponding actual parameter.
When you attach & after the datatype in the formal parameter list of a function, the
variable following that datatype becomes a reference parameter. When a function is called,
the value of the actual parameter is copied to the formal parameter. If the formal parameter is
a value parameter, then after copying the value of the actual to the formal parameter, there is
no connection between the formal and actual parameters because the formal parameter has
now its own copy of the data. Therefore, at run time, the formal parameter manipulates the
data stored in its own memory space.
Encode the following program below and observe how a value parameter works (pass by
value).
#include<iostream>
using namespace std;
int main()
{
int number = 6;
cout << “Before calling the function fValueParameter, number = “
<< number << endl; fValueParameter(int num);
cout << “ After calling the function fValueParameter, number =
“
<< number << endl; return 0;
}
After copying the data from actual to formal, a value parameter has no connection with
the actual parameter. Therefore, a value parameter cannot pass any result back to the calling
function. When the function executes, any changes made to the formal parameters do not in
any way affect the actual parameters. Value parameters provide only a one-way link between
actual and formal parameters.
Encode the program below and observe how passing variables by reference works
#include<iostream> using
namespace std; void
getAge(int &inYears);
void displayAge(int years);
int main()
{
int age = 0;
getAge(age);
displayAge(age);
return 0;
}
Remember that when you pass a variable by a value, the computer uses the data type
and name of its corresponding formal parameter to create a separate memory location in
which to store the value. When you pass a variable by reference, on the other hand, the
computer locates the variable in memory and then assigns the name of its corresponding
formal parameter to the memory location. When you pass a variable by reference, the
variable will have two names: one assigned by the calling function and the other assigned by
the receiving function. Value-returning functions, on the other hand, send information back to
the calling function through their return value.
Self-Help: You can also refer to the sources below to help you
further understand the lesson
[1] G. Bronson, C++ Programming Principles and practices for scientists and engineers,
Boston: Cengage Learning, 2013.
[2] D. Malik, C++ Programming: from problem analysis to program design, Stamford:
Cengage Learning, 2015.
[3] J. Smith, C++ programs to accompany logic and design 8th edition, Boston: Cengage
Learning, 2015.
[4] D. Zak, An introduction to programming with C++ (8th Edition), Andover: Cengage
Learning, 2016.
[5] M. Main, Data structures and other objects using c++, Boston: Pearson, 2011.
In a Nutshell
79
There are two types of programming functions: pre-defined and programmer defined. Pre-
defined functions are built-in to C++ compiler. In order for a pre-defined function to work,
declare the appropriate header file. e.g. declare #include<iomanip> if any of the function
for formatting floating point numbers is necessary.
To create a programmer defined function, one must declare the function first, define the
function body and do a function call. For a sleeker output, one can create its own hex file to
keep the preprocessor file.
80
calcCelsius
function Fahrenheit Processing items: none Celsius temperature
temperature
Algorithm:
1. Celsius temperature =
5.0 / 9.0 * (Fahrenheit
temperature – 32.0)
2. Return the Celsius
temperature
ULO(3-a) Task B: Write down your observations and learnings of the above activity.
Minimum of 50 words.
Create IPO charts for the problem. List the input, processing and output items, as
well as the algorithm, in a chart similar to the one shown in Task A. Code the algorithm
into a program.
Q&A List
Please write your queries on the table provided below:
81
Questions Answers
Ratings
Parameters
3 2 1
Source code contains no Source code contains Source code contains
Syntax syntax error. 1 to 5 syntax errors. more than 5 syntax
(30%) (30) (20) errors.(10)
Source code contains the Source code lacks Source code is not
Specifications complete details to run necessary details to enough to run the
(30%) the program correctly. run the program program correctly.
(30) correctly.(20) (10)
Source code is well Minor issues such as Major issues are
Readability organized and easy to variable naming, causing the codes to
(10%) understand. variable utilization, be not readable.
(10) etc. are observed. (6) (3)
Source code is well Source code allows Source code does not
Screen Output organized and easy to the required screen meet the required
(10%) understand. output to be displayed screen output to be
correctly with 1-3 displayed correctly.
(10) errors found.(6) (3)
82
The documentation is The documentation The documentation
well written and lacks some didn’t satisfy all the
Documentation clearly explained all information and some questions that were
(20%) the mistakes are found in given in the laboratory
questions given in the the questions. exercise.
laboratory exercise. (14) (7)
(20)
Metalanguage
This section will discuss concepts on array, character and numeric type. It will
emphasize the importance of using array over other programming structure in order to
demonstrate ULO 3-b; be able to create a program using a single-dimension array.
Essential Knowledge
83
Each students score is equally important hence each record must not be override which is
usually the case of a single variable declaration used within a loop. The use of array offers a
convenient way of creating list of related variables. There can only be one declaration for the
list of values related to each other giving us the advantage of not declaring multiple variable
names yet it gives us control to each element on an array. Array oftentimes work with any
form of looping structure which was presented on laboratory exercise 5, therefore it is
imperative that a better understanding on how looping structure as well as array on its own
work before embarking on this exercise.
There are different dimensions to be used in array. It may have from one to several
dimensions but the commonly used are the one-dimensional array and two-dimensional array.
A one-dimensional array is coded as:
variable_type name[size];
The type refers to the data type for the elements making up the array. Names refers to
the array name similar to that of the variable name. Additional feature is the size of the array.
The size determines the number of elements that the array can hold. The size also determines
the index of the individual element. Example declaration of an array can be:
int varone[10];
Given the declaration above we can say that the array holds 10 elements. Each
element of an array is accessed through its index. The index is used to describe the position
of an element within the given array. It starts with zero index indicating the first element.
From the given we can say that varone has index values from 0 to 9. Accessing a particular
index is coded as varone[0] which is the first element of the array. Varone has elements
from varone[0] through varone[9].
84
As you can with simple variable, you can use either an assignment statement or the
extraction operator to enter data into an array element.
Syntax
arrayname[subscript] = expression;
Example 1:
char letters[3]; //declares a three element array
letter[1] = ‘Y’; //assigns the letter Y to the second element
// in the letter array
Example 2:
int numbers[6];
int x;
for(x = 1; x <= 6; x++)
numbers[x – 1] = pow(x,2); // end of loop
// assigns the squares of the numbers from 1 through 6 to the
// six-element
// numbers array
Example 3:
int x, increase = 0; int
numbers[6]; cout<< “enter
increase amount : “; cin>>
increase; for( x = 0; x < 6; x++)
numbers[x] = numbers + increase; // end of loop
Assigns to each element in the six-element numbers array, the sum of the element’s current
value plus the value stored in the increase variable.
Syntax:
cin>>arrayName[subscript];
85
Example 1:
char letters[5];
int sub;
int sales[4];
for (sub = 0; sub < 4; sub++)
{
cout<<“ Enter the sales for Region “;
cout<< sub + 1 << ”: “; cin>>
sales[sub]; } // end of for loop
//stores the user’s entries in the four-element sales array
To display the contents of an array, you need to access each of its elements. You do this
using a loop along with a counter variable that keeps track of each subscript in the array.
Example 1:
int x = 0;
char letters[3]; x
= 0; while (x < 3)
{
cout<< letters[x] <<endl;
x++;
} // end of while loop
// displays the contents of the three element letters array
Example 2:
int sub, int sales[4];
for(sub = 0; sub < 4; sub++)
{
cout<< “Sales for Region “ << sub + 1 << “: $”;
cout<< sales[sub] <<endl;
} // end of for loop
// displays the contents of the four-element sales array
Program Requirements:
1. Declare a single dimension array of size n
2. Input n elements to a single dimension array
3. Sort the elements of an array from highest to lowest and vice versa
Also, the program will identify and output the highest and lowest integer.
Self-Help: You can also refer to the sources below to help you
further understand the lesson
[1] G. Bronson, C++ Programming:principles and practices for scientists and engineers,
Boston: Cengage Learning, 2013.
[2] D. Malik, C++ Programming: from problem analysis to program design, Stamford:
Cengage Learning, 2015.
[3] J. Smith, C++ programs to accompany logic and design 8th edition, Boston: Cengage
Learning, 2015.
87
[4] D. Zak, An introduction to programming with C++ (8th Edition), Andover: Cengage
Learning, 2016.
[5] M. Main, Data structures and other objects using c++, Boston: Pearson, 2011.
Q&A List
Write your questions on the table provided.
Questions Answers
88
Source code is well Minor issues such Major issues are
Readability organized and easy as variable causing the codes to
(10%) to understand. naming, variable be not readable.
(10) utilization, (3)
etc. are observed.
(6)
Source code is well Source code allows Source code does
Screen Output organized and easy the required not meet the
(10%) to understand. screen output to required
be screen output to
(10) displayed correctly be
with 1-3 errors displayed
found.(6) correctly.
(3)
The documentation is The documentation The documentation
well written and clearly lacks some didn’t satisfy all the
Documentation explained all the information and questions that were
(20%) questions given in the some mistakes are given in the
laboratory exercise. found in the laboratory
(20) questions. exercise.
(14) (7)
Metalanguage
This section will discuss the concept on two-dimensional array, its importance over
other programming structures. In addition, it will also illustrate how to manipulate the use of a
multiple array in order to demonstrate ULO 3-c; be able to create a program using multi-
dimensional array.
89
Essential Knowledge
Example 2:
double prices[6][5] = {2.0};
90
Entering Data into a Two-Dimensional Array
As you can with one-dimensional arrays, you can use either an assignment statement
or the extraction operator to enter data into the elements of a two-dimensional array.
arrayName[row][col] = expression;
Example 1:
char grades[1][0] = ‘F’;
// assigns the letter F to the element located in the second row, first
// column in the grades array
Example 2:
int row, column;
int orders[4][3];
cin>>arrayName[subscript][subscript];
Example 1:
cin>>grades[2][1];
// stores the user’s entry in the element located in the third row,
// second column in the grades array
91
Example 2:
int region, month, orders[4][3];
for( region = 0; region < 4; region ++)
for( month = 0; month < 3; month++)
{
cout<< “Number of orers for Region “
<< region + 1 <<“ , Month ”
<< month + 1 <<“ : “;
cin>> orders[region][month];
} // end of inner loop
// end of outer loop
// stores the user’s entries in the four-row by three-column orders
// array, region (row) by region (row)
To display the contents of a two-dimensional array, you need to access each of its elements.
You do this using two counter-controlled loops; one to keep track of the row and the other for
the column subscript.
Example 1:
for( int region = 0; region < 4; region++)
for( month = 0; month < 3. month++)
cout<< orders [region][month] <<endl;
// end of inner loop
// end of outer loop
// displays the contents of the four-row, three-column orders array, region (row) by region
(row).
Example 2:
int row = 0;
int column = 0;
while (column
< 2)
{
while ( row< 3)
{
cout<< grades[row][column] <<endl;
92
row++;
} // end of inner while loop
column++;
row = 0;
} // end of outer while loop
// displays the contents of the three-row, tow-column grades array,
// column by column
ULO(3-c) Task A
Declare a seven-row, two-column int array named temperatures. The program
should prompt the user to enter the highest and lowest temperatures for seven days. Store
the highest temperatures in the first column in an array. Store the lowest temperatures in the
second column. The program should display the average high temperature and the average
low temperature. Display the average temperatures with one decimal place.
=================================
Day Highest Lowest
=================================
1 95 67
2 98 54
3 86 70
4 99 56
5 83 34
6 75 68
7 80 45
Average high temperature: ____
Average low temperature: ____
Questions:
1. If the dimension for array temperature is 7 rows and 2 columns, how many instances the
inner loop iterates? How about the outer loop?
93
2. How was it made possible for the program to determine the average high temperature
and average low temperature?
Self-Help: You can also refer to the sources below to help you
further understand the lesson
[1] G. Bronson, C++ Programming:principles and practices for scientists and engineers,
Boston: Cengage Learning, 2013.
[2] D. Malik, C++ Programming: from problem analysis to program design, Stamford:
Cengage Learning, 2015.
[3] J. Smith, C++ programs to accompany logic and design 8th edition, Boston: Cengage
Learning, 2015.
[4] D. Zak, An introduction to programming with C++ (8th Edition), Andover: Cengage
Learning, 2016.
[5] M. Main, Data structures and other objects using c++, Boston: Pearson, 2011.
In a Nutshell
An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type. Arrays can be a single-dimensional or
twodimensional array. In single-dimensional array, a simple variable may store only one
value at a time under its name and a structure/composite type that may store a list of values
all of the same data type. A two-dimensional array is used to represent a table (rows &
columns) of items all of the same type. Arrays are an important complex data type used in
almost all programming because it allows us to store a single value at a time, what if we want
to store roll no. of 50 students? For this task, we have to declare 50 variables, then assign
values to each of them. What if there are 20000 students or more? As you can see declaring
that many variables for a single entity (i.e student) are not a good idea. In a scenario like
these arrays provide a better way to store data.
94
Q&A List
If you have any questions, kindly write down on the table provided.
Questions Answers
95
Laboratory Exercise Rubric for Programming
Ratings
Parameters
3 2 1
Source code contains Source code Source code
Syntax no syntax error. contains 1 to 5 contains more than
(30%) (30) syntax errors. 5 syntax errors.(10)
(20)
Source code contains Source code Source code is not
Specifications the complete details lacks necessary enough to run the
(30%) to run details to run program correctly.
the program the program (10)
correctly. correctly.(20)
(30)
Source code is well Minor issues such Major issues are
Readability organized and easy as variable causing the codes to
(10%) to understand. naming, variable be not readable.
(10) utilization, (3)
etc. are observed.
(6)
Source code is well Source code allows Source code does
Screen Output organized and easy the required not meet the
(10%) to understand. screen output to required
be screen output to
(10) displayed correctly be
with 1-3 errors displayed
found.(6) correctly.
(3)
96
The documentation is The documentation The documentation
well written and clearly lacks some didn’t satisfy all the
Documentation explained all the information and questions that were
(20%) questions given in the some mistakes are given in the
laboratory exercise. found in the laboratory
(20) questions. exercise.
(14) (7)
Approved by:
Charlito L. Canesares,DEngg(ME)
Name of Dean
97