0% found this document useful (0 votes)
187 views94 pages

Sim For Edp 101l

This document is a self-instructional manual for a computer fundamentals and programming course offered online with occasional face-to-face sessions. It outlines the course details, including 9 units of content organized by learning outcomes, essential knowledge, self-help exercises, and assessment questions for each unit. The course aims to engage students in self-directed online learning with support from scheduled virtual sessions and a manual providing foundations of computer science and programming fundamentals.
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)
187 views94 pages

Sim For Edp 101l

This document is a self-instructional manual for a computer fundamentals and programming course offered online with occasional face-to-face sessions. It outlines the course details, including 9 units of content organized by learning outcomes, essential knowledge, self-help exercises, and assessment questions for each unit. The course aims to engage students in self-directed online learning with support from scheduled virtual sessions and a manual providing foundations of computer science and programming fundamentals.
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/ 94

UNIVERSITY OF MINDANAO

College of Engineering Education


Computer Engineering Program

Physically Distanced but Academically Engaged

Self-Instructional Manual (SIM) for Self-Directed Learning (SDL)


Week 1-9(updated)

EDP101/L – Computer Fundamentals and Programming


Engr. Hanna Leah P. Angelia

THIS SIM/SDL MANUAL IS A DRAFT VERSION ONLY; NOT FOR


REPRODUCTION AND DISTRIBUTION OUTSIDE OF ITS INTENDED
USE. THIS IS INTENDED ONLY FOR THE USE OF THE STUDENTS WHO ARE OFFICIALLY
ENROLLED IN THE COURSE/SUBJECT.
EXPECT REVISIONS OF THE MANUAL.
Table of Contents

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
Laboratory Rubric……………………………………………………………………………. 56
Big Picture in Focus: ULO-2c…………………………………………………………………..….. 57
Metalanguage………………………………………………………………………………….. 57
Essential Knowledge………………………………………………………………………… 57
2
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

Course Coordinator: Engr. Hanna Leah P. Angelia


Email: hangelia@umindanao.edu.ph
Student Consultation: By appointment
Mobile: 09231046742
Phone: (082) 2961084 or 3050647 loc. 133
Effectivity Date: May 25, 2020
Mode of Delivery: Blended (On-Line with face to face or virtual sessions)
Time Frame: 108 Hours
Student Workload: Expected Self-Directed Learning
Requisites: None
Credit: 2 units laboratory
Attendance Requirements: A minimum of 95% attendance is required at all scheduled
Virtual or face to face sessions.

Course Outline Policy

Areas of Concern Details


Contact and Non-Contact Hours This 2-unit laboratory course self-instructional manual is
intended for blended learning mode of instructional delivery
with scheduled face-to-face or virtual sessions. The
expected number of hours will be 90, including the face-to-
face or virtual sessions which will be arranged by the course
coordinator. The face-to-face sessions shall include the
summative assessment tasks or examinations since this
course is vital in the licensure examination for engineers.

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.

Since this course is included in the licensure examination


for engineers, you will be required to take the Multiple
Choice Question exam inside the University as your final
exam. This should be scheduled ahead of time by your
course coordinator. This is non-negotiable for all licensure
based programs.

4
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.
Assignment Resubmission You should request in writing addressed to the course
coordinator your intention to resubmit an assessment task.
The resubmission is premised on the student’s failure to
comply reasonable circumstances e.g. illness, accidents
financial constraints.

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.

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%

All culled from on-campus/onsite sessions (TBA): Final


exam – 40%
Submission of the final grades shall follow the usual
University system and procedures.

5
Student Communication You are required to create a umindanao email account
which is a requirement to access the BlackBoard portal.
Then, the course coordinator shall enroll the students to
have access to the materials and resources of the course.
All communication formats: chat, submission of
assessment tasks, requests etc. shall be through the
portal and other university recognized platforms.
You can also meet the course coordinator in person
through the scheduled face to face sessions to raise your
issues and concerns.
For students who have not created their student email, please
contact the course coordinator or program head.
Contact Details of the Dean Dr. Charlito L. Cañesares, PME
Email: clcanesares@umindanao.edu.ph
Phone: 082-296-1084
Contact Details of the Program Head Engr. Randy E. Angelia, MEP-ECE, MSCpE
Email: randy_angelia@umindanao.edu.ph
Phone: (082) 296-1084/09423595648
Students with Special Needs Students with special needs shall communicate with the
course coordinator about the nature of his/her special needs.
Depending on the nature of the need, the course coordinator
with the approval of the program head may provide alternative
assessment tasks or extension of the deadline of submission
of assessment tasks. However, the alternative assessment
tasks should still be in the service of achieving the desired
course learning outcomes.
Help Desk Contact CEE Blackboard Administrator:

Engr. Jetron A. Adtoon, MSCpE


Email: jadtoon@umindanao.edu.ph
Phone: +63 9055 267834

CEE:
Frida Santa O. Dagatan
Email: cee@umindanao.edu.ph
Phone: +63 9055 267834

GSTC:
Ronadora E. Deala, RPsy, RPm, RGC, LPT
Email: ronadora_deala@umindanao.edu.ph
Phone: +63 921 2122846

Silvino P. Josol
Email: gstcmain@umindanao.edu.ph
Phone: +63 906 0757721
Library Contact Brigida E. Bacani
Email: library@umindanao.edu.ph
Phone: +63 951 3766681

6
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. Utilization 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!

7
Big Picture
Week 1-3: Unit Learning Outcomes-UNIT 1 (ULO-1): At the end of the unit, you are
expected to:

a. review concepts and principles of different elements and generation of a computer


system.
b. apply principles and concepts of different number systems and its relation to
computer system, and
c. understand computer programming principles and apply tools in developing program
logic.

Big Picture in Focus:


ULO-1a. review concepts and principles of different elements and generation of a
computer system

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.

1. Computer. It is an electronic device capable of storing, retrieving, and processing


data into useful information.
2. Computer Program. Instructions or codes feed into the computer memory to make
or perform it do something
3. Programmer. The person who writes instructions (programs) to make the computer
perform a task
4. Computer Systems. The computer system is divided into two main components:
Computer Hardware and Computer Software

8
4.1 Computer Hardware refers to the TANGIBLE materials in the computer system and
divided into five main categories namely:

Central Processing Unit (CPU)


Main memory (RAM)
Secondary storage devices
Input Devices Output Devices

4.1.1 Central Processing Unit.


Central Processing Unit or CPU is an electronic circuitry within a computer that
executes instructions. It promises with Arithmetic and Logic Unit or (ALU) that
performs basic arithmetic and logic analysis as well as Control Unit (CU) that
coordinates computer operation and input/output operations.

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

4.1.3 Secondary Storage Devices (SSD). This refers to computer memory, but a
non-volatile type, meaning data retained when the program is not running or
computer is turned off—examples of SSD floppy disk, hard disk drive, CD or DVD
or USB flash drive.

4.1.4 Input Devices. Input devices are computer components use to send
information to the computer from

4.1.5 Output Devices. Output devices are computer components use to send
information from the computer to the outside. Computer screen, printer, speakers,
disk drive, CD/DVD recorder, USB flash drive.

9
4.2 Computer Software. Software is a program that enables a computer to perform
specific task. Computer systems categorize computer software into three different classes.
Namely, the operating system, programming language, and application software.

4.2.1 Operating Software is programs that manage the computer hardware and
the applications that run on the computer. Ex. Windows, Linux, Unix,Mac
4.2.2 Programming Language is a set of commands, instructions and other
syntax used to create application software. Examples of programming languages
are C++,Java, Visual Basic, DevC++ and many more.
4.2.3 Application Software is a product of programming language that performs
a specific task. Application software are designed to assist the user with a
particular process.

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.

Overview of the History and Generations of Computer

First Generation of Computer (1946-1959)


The computers of first-generation used vacuum tubes as the necessary components for
memory and circuitry for CPU (Central Processing Unit). These tubes, like electric bulbs,
produced a lot of heat, and the installations used to fuse frequently. Therefore, they were
costly and only large organizations were able to afford it.
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.

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

Figure1. ENIAC (www.computerhoop.com)

Figure2. UNIVAC(www.computerhistory.org)

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

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

Third Generation of Computer (1965-1971)


The computers of the third generation used Integrated Circuits (ICs) in place of transistors.
A single IC has many transistors, resistors, and capacitors, along with the associated
circuitry. The IC was invented by Jack Kilby. This development made computers smaller in
size, reliable, and efficient. In this generation, remote processing, time-sharing,
multiprogramming operating system were used. High-level languages such as FORTRANII
TO IV, COBOL, PASCAL PL/1, BASIC, ALGOL-68, etc. were used during this generation.

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.

Fourth Generation of Computer (1971-1980)


Computers of fourth-generation used Very Large Scale Integrated (VLSI) circuits. VLSI
circuits having about 5000 transistors and other circuit elements with their associated
circuits on a single chip made it possible to have microcomputers of the fourth generation.
This is commonly known as microprocessors.
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.

12
Fifth Generation of Computer (1980-present)
In the fifth generation, VLSI technology became ULSI (Ultra Large Scale Integration)
technology, resulting in the production of microprocessor chips having ten million electronic
components.
This generation is based on parallel processing hardware and AI (Artificial Intelligence)
software. AI is an emerging branch in computer science, which interprets the means and
methods of making computers think like human beings. All the high-level languages like C
and C++, Java, .Net etc., are 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.
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.

13
Let’s Analyze!
1. What is the difference between System software and application software?

2. In the generations of computers both VLSI and ULSI is called microprocessor or


microchip of CPU. But what is the difference between the two?

3. What probably is the main reason why the sizes of a computer significantly reduced
from the first generation to the recent?

4. How CPU works to connect input devices to the output devices?

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.

• The computer has an electronic circuitry called microprocessor that made up of


thousands of transistors that fetch and execute instructions.

Q&A List
If you have questions about computer system, kindly write down on the table provided.
Questions Answers

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

Decimal Number System


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.

Decimal to other Base System


To convert a decimal number to other number system, do the following steps:

15
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:

Convert 79.62510 - > ____ 2


Step Operation Result Remainder
1 79/2 39 1
2 39/2 19 1
3 19/2 9 1
4 9/2 4 1
5 4/2 2 0
6 2/2 1 0
7 1/2 0 1
Table 1 Decimal to Binary Conversion (Whole number part)
The remainders have to be arranged in reverse order so that the first remainder
becomes the LSD, and the last remainder is the MSD. For the fractional part, you may do
the following steps.
Step 1: Multiply the fractional part by the base you are converting into.
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.

16
Example:
Convert 0.62510 - > _____2

Step Operation Whole number Fractional Part


1 .625 x 2 1 .25
2 .25 x 2 0 .5
3 .5 x 2 1 .0
Table 2 Decimal to Binary Conversion (Fractional Part)

Answer: 79.62510 - > 1001111.1012

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

Step Binary Number Decimal Number


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

17
8 = 23 16 = 24

Therefore:
 3 digits in base-2 (binary) is equivalent to 1 digit in base – 8 (octal)

 4 digits in base-2 (binary) is equivalent to 1 digit in base -16 (hexadecimal)

Binary Number System


The binary number uses only two digits, 0 and 1. Each position in a binary number
represents a 0 power of the base (2). The last position in a binary number represents a x
power of the base (2). Example 2 x where x represents the last position - 1.
Binary Number Calculations
Example 1: Find the equivalent decimal number of a binary number 1010 2.

Steps Binary Number Decimal Number


Step 1 10102 ((1x2 )+( 0x2 )+( 1x21)+( 0x20))10
3 2

Step 2 10102 (8+0+2+0)10


Step 3 10102 1010
Table 4. Steps in solving binary to decimal

Example 2: Find the equivalent octal number of a binary number 1010 2.


Step 1. Group the given binary number to 3 bits starting from the Least Significant
Bit(LSB) or the rightmost side of the number. In the event that the remaining
binary number is less than 3 digit, ADD zero (0) to the right significant bit to make
it 3 bits.
Given Groups
10102 = Ι 001 Ι Ι 010 Ι

Step 2. Compute each group individually following the process in example 1.


Ι 001 Ι Ι 010 Ι
2 1 0
(0x2 + 0x2 + 1x2 )8 (0x2 + 1x21 + 0x20 )8
2

(0+0+1)8 (0+2+0)8

Step 3. Gather the result.


18
Answer : 10102 = 128

Example 3. Find the equivalent hexadecimal number of a binary number 1010 2.

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

(8+0+2+0)16 = 10; but 10 is equal to A in base16;therefore

Step 3. Gather the result.

Answer : 10102 = A16

Octal Number System

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

Octal Number Calculations


Example 1: Find the equivalent decimal number of an octal number 123 8.

Steps Binary Number Decimal Number


Step 1 1238 ((1x8 )+( 2x8 )+( 3x80))10
2 1

Step 2 1238 (64+16+3)10


Step 3 1238 8310
Table 5. Steps in calculating Decimal to Octal numbers
Example 2: Find the equivalent binary number of an octal number 123 8.
19
Step 1. Get the equivalent 3-bits value of each octal digit.

18 = 0012
28 = 0102
38 = 0112

Step 2. Gather all the results


Answer : 1238 = 0010100112

Example 3: Find the equivalent hexadecimal number of an octal number 1238.


Step 1. Get the equivalent 3 bits value of each octal digit.

18 = 0012
28 = 0102
38 = 0112
Step 2. Gather all the result for the binary
Answer : 1238 = 0010100112

Step 3. Group the binary result of the given octal number by 4 bits starting from the
LSB, then gather the hexadecimal result.
Given Group/s
0010100112 = Ι 0000 Ι 0101 Ι 0011 Ι
= Ι0 Ι 5 Ι 3 Ι

Step 4. Gather all the results


Answer : 0010100112 = 05316 or 5316

Hexadecimal Number System

Hexadecimal number system uses 10 digits and 6 letters


(0,1,2,3,4,5,6,7,8,9,10,A,B,C,D,E,F). The numerical equivalent of each letters are as
follows: A=10, B=11, C=12, D=13, E=14, F=15. Each position in a hexadecimal number
represents a 0 power of the base (16). And the last position in a hexadecimal number

20
represents a x power of the base (16). Example 16 x where x represents the last position -
1
Calculating decimal equivalent of the hexadecimal number.

Example 1: Find the equivalent decimal number of the Hexadecimal number 10A 16.

Steps Binary Number Decimal Number


Step 1 10A16 ((1x16 )+( 0x16 )+( 10x160))10
2 1

Step 2 10A 16 (256+0+10)10


Step 3 10A 16 26610
Table 6. Steps in converting decimal to hexadecimal number system.

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 ABC 16.
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
1010101111002 = Ι 101 Ι 010 Ι 111 Ι 100 Ι
21
=Ι 5 Ι 1 Ι 7 Ι 4 Ι

Therefore : ABC16 = 1010101111002 = 51748

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
Convert the given values based on the required number system.

1. 1010 = _________2 = _________8 = _________16


2. 111011012 = _________10 = _________8 = _________16
3. 5768 = _________2 = _________10 = _________16
4. CAB16 = _________2 = _________8 = _________10

22
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

23
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
5. Display results.

Example 2: An algorithm to find the largest among three different numbers entered by the
user.

1: Declare variables a,b and c.


2: Read variables a,b and c.
3: If a > b
if a > c
display a is the largest number.
else
display c is the largest number.
24
else
if b > c
display b is the largest number.
else
display c is the greatest number.
4: Stop

Example 3: An algorithm to find the factorial of a number entered by a user.

1: Declare variables n, factorial and i.


2: Initialize variables
factorial ← 1
i←1
3: Read value of n
4: Repeat the steps until i = n
5.1: factorial ← factorial*i
5.2: i ← i+1
5: Display factorial
6: Stop

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.
Begin
input length, width
perimeter = 2 * (length + width)
area = length * width
print perimeter
print area
End

Example 2: A pseudocode to Calculate the Sum and Average of 10 numbers.

Begin

25
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

Example 3: A pseudocode in computing the Fibonacci numbers till 50.

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

A flowchart is a graphical representation of an algorithm. It is usually drawn using certain


special-purpose symbols connected by arrows called flow lines. Table 7 shows the basic
flowchart symbols with its equivalent meaning.

26
Flowchart Symbol Meaning

Terminal

Input/output operation

Process

Initialization

Pre-defined process

Off-page connector

On page connector

Decision

Flow lines

Table 7. Figures used in Flowcharting

27
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

Figure 4 (Sum of two numbers) shows an example of pseudocode with an equivalent


flowchart. It illustrates that the program needs values for variables x and y. Then, the
program will compute for the total and contain the result through the variable sum. After
solving for the sum, the result will be displayed to the screen.

28
Pseudocode Flowchart

Begin
initialize x and y
input x and y sum
= x+y
print sum
End

Figure 4. Sum of two numbers (pseudocode and flowchart).

Diamond shape or decision symbol in the flowchart is usually used in representing


the decision making or selection process in the program. Shown in Figure 5 (multiple
Selection) is an example of multiple selection processes wherein the application will locate
where the particular input belongs.

29
Pseudocode Flowchart

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

Figure 5 Multiple Selection

Figure 6 showcase the example of an iterative flowchart. An iterative flowchart is usually


utilized in program loops where the program will keep on repeating the same code or line
of codes until the certain condition is satisfied.

30
Pseudocode Flowchart

Begin
i=0 sum = 0 while
i<10 input x sum
= sum +x
++i avg =
sum / 10 print
avg
End

Figure 6. Pseudocode and Flowchart of an Iterative Statement

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.

31
Let’s check!

ULO-1c: Task 1
Given below is the pseudocode on how to compute the overtime pay of the employee.

Begin
input hours, rateperhour
if hours >25
pay = hours * (rate*1.45)
print pay
if hours >10 but <25
pay = hours * (rate*1.25)
print pay
if hours <10 pay =
hours *rate
print pay
End

ULO-1c: Task 2

1. Draw the equivalent flowchart of the given pseudocode.

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

32
Algorithm:
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.

33
Q&A List
If you have any questions, write on the blank below.
Questions Answers

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

Big Picture in Focus:


ULO 2-a. to understand and apply operators, input/output programs and
hierarchies of computer programming.

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

1. double num1 = 5, num2, sum;


2. num2 = 12;
3.
4. sum = num1 + num2;
6. Statement: it is an instruction to the computer to perform an action. It may contain
keywords, operators, program defined identifiers, and punctuation. It could fit in one line
or it may occupy multiple lines.
Example: Line 1 and 2 is a statement, notice that the end of line on is just a
comma (,) while line 2 ends semicolon(;).
1. double num1 = 5,
2. num2, sum;
7. Syntax: a set of rules in computer programming that governs the ruling of the
programming language.
8. Source code: The text of a program that a user can read; commonly thought of as a
the program. The source code is input to the C compiler.
9. Object code: Translation of the source code of a program into machine code, which the
computer can read and execute directly. Object code is the input to the linker.

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

36
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
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
37
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

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

39
Programming Process

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.

C programming language supports several mathematical functions that are


predefined such as basic mathematical and trigonometric operations. To use the predefined
function in a program, you need to know the name of the header file containing the
specification of the function and include that header file in the program. In addition, you
need to know the name of the function, the number of parameters the function it takes, and
the type of each parameter.

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.

Functions Meaning Example Preprocessor


pow(x,y) pow(base,exponent) pow(4,2) cmath/Math.h

log(x) natural log of x log(5) cmath/Math.h

exp(x) exponential value of exp(5) cmath/Math.h


x
cos(x) cosine of x cos(60) cmath/Math.h

sin(x) sine of x sin(60) cmath/Math.h

tan(x) tan of x tan(60) cmath/Math.h

acos(x) arccos of x acos(60) cmath/Math.h

40
asin(x) arcsin of x asin(60) cmath/Math.h

atan(x) arctan of x atan(60) cmath/Math.h

fabs(x) absolute value of x fabs(-10) cmath/Math.h

sqrt(x) square root of x sqrt(10) cmath/Math.h


Table 11. Mathematical Functions

* M_PI stands for constant PI.


* By default, answers for trigonometric functions will return radian values
* In order to get the value in degrees multiply the angle to (M_PI/180)

Functions Meaning Example


setprecision(n) Control the output of cout << setprecision(3)<<
floating-point numbers
fixed Set to output in fixed cout << fixed<<
decimal format until it is
disabled
(cout.unsetf(ios::fixed)
showpoint To force the output to cout << showpoint<<
show the decimal point
and trailing zeros.
setw(n) To output the value of an cout << setw(10)<<
expression in a specific
number of columns and is
right-justified.

Table 12. Formatting Output Functions

Let’s check and Analyze!


ULO(2-a) Task A
Test the given code by typing it to your DevC++ IDE. This program is designed to
solve for the value of y in the mathematical equation y = x4 – 5x3 + 3x2 - 2x.
1 #include<iostream>
2 #include<math.h>
3 using namespace std;
4

41
5 double x, y; // variables
6 int main()
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:

1. What is the value of y if x = 30.15?


2. Explain the code in lines 10 and 11.
3. What would be the outcome of the statement below if lines 10 and 11 were
interchanged?

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.

42
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:_______

Check by Mollweide’s Equation:


__________ = _________
Figure 5 Case 4: Oblique Triangle

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

43
Big Picture in Focus:
ULO(2-b) to apply logic program structures using sequence and
selection/decision process.

Metalanguage

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.

The preceding laboratory shows how a computer program process in sequence while
on this laboratory exercise focuses mainly on the discussion of the different methods in
using the if statements control structure, which is another way of processing a program; by
making a choice.

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
44
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
Table 13. Relational Operators

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.

Operator Symbol Precedence


> >= < <= Highest
== != Lowest
Table 14. Relational Operators Hierarchy

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;

The expression in an if statement can be a relational expression or a combination


of relational and logical expressions. If the value of the expression is true, the statement
executes. If the value is false, the statement does not execute, and the computer goes on
to the next statement in the program.

Sample Program Condition A:

// This program prints "You Pass" if a student's average is 60


// And prints “A+” if student's average is greater than 95

#include <iostream>
using namespace std;

int main()
{
float average;

45
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 <<
"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.

If…else statement is a control that executes a block of code if a Boolean expression


evaluates to true. It uses the statement under the keyword else if the above condition is
false.

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:

if (average >= 60) cout << "You


Pass" << endl;
else cout << "You Fail" <<
endl;

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

Multiple Selection: Nested if

Syntax:

if (condition1)
{
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.

Sample Program Condition B

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;
47
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"
<< 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.

48
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:

If (age >= 18 && residency >= 6)


cout<< “ qualified voter ”;
else
cout<< “ not eligible to vote “ ;

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

The switch statement executes according to the following rules:

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

// This program illustrates the use of the switch statement.

#include <iostream>
using namespace std;

int main()
{
char grade;

cout << "What grade did you earn in Programming 1?"


<< endl;
cin >> grade;

switch( grade ) // This is where the switch statement begins


{
case 'A': cout << "an A - excellent work !" << endl;
break;
case 'B': cout << "you got a B - good job" << endl;
break;
case 'C': cout << "earning a C is satisfactory" << endl;
break;
case 'D': cout << "while D is passing, there is a problem"
<<endl;
break;
case 'F':
cout << "you failed - better luck next time"
<< endl;
break;
default:
cout << "You did not enter an A, B, C, D, or F"
<< endl;
} // end of switch statement
50
return 0;
}

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 and Analyze!

ULO(2-b) Task A: Conditional Statement (if…else if)


Create a program that computes the general average and display the remarks of the
corresponding grade. Implement using if…else or laddered if/else if conditions Program
Requirements:
1. The program will ask the user to input scores for examinations, quizzes, laboratory
exercises, and laboratory projects. Please refer to figure 5 (sample screen display).
2. It shall only accept inputs ranging from 0 - 100.
3. A Base-15 grading system shall be used to compute the grades.
(raw score / no. of items) * 85 + 15;
4. Please refer to figure 3.2 for the assigned weights of each activity.
5. After keying in all inputs, the Final Grade and Remarks will be shown.
6. The program will allow to key in another set of inputs if an <Enter Key> is pressed
and exit for any other key (use ASCII code of Enter Key, 13).
7. Display the remarks as the output on the following given scale. Please refer to figure
7

51
Computation of Grades

Major Examinations (100 pts each) Quizzes (40 pts each)


First : _______ Qz # 1 : _____
Second: _______ Qz # 2 : _____
Third : _______ Qz # 3 : _____
Final : _______
Laboratory Exercises (50 pts each)
Exer # 1 : _______
Exer # 2 : _______
Exer # 3 : _______
Exer # 4 : _______
Laboratory Project (100 pts): ________
Gen. Av. : _________
Remarks : _________
Press <Enter Key> to Re-run the Program
Press <any key> to exit

Figure 5 Computations of Grades.

Weights Assignment

First Examination 10% Laboratory Exercise 10%


Second Examination 10% Quizzes 10%
Third Examination 10% Laboratory Project 20%
Final 30%

Figure 6 Weights assignment

General Average Remarks


100 – 95 Excellent
94 - 90 Very Good
89 - 85 Good
84 – 80 Satisfactory
79 – 75 Fair
Below 75 Failed

Figure 7. Equivalent Remarks.


52
Questions:
1. What is the process used to compute the general average?
2. What programming structure is used, enabling the program to select appropriate
grade remarks?
3. How many segments of the “if-else” statement are needed to show appropriate
remarks of the gen. average?
4. What logical and relational operators where used to state appropriate range of
grades?
5. l operators were used to state the appropriate range of grades?
6. Write the complete pseudocode of the program.

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.

53
Main List Option

[A] Perimeter
[B] Area
[C] Surface Area
[D] Exit
Enter Option: ____A_____

Figure 8 Main Menu Screen Output

Perimeter
Geometric Figure
1] Square
2] Rectangle
3] Back to Main List of Options
Enter Option: 1

Figure 9 Perimeter Screen Output

Square
Enter side measurement of the square: 4.25 inches

The perimeter of a square with a side measurement

of 4.25 inches

is _17.00 inches

Press < K > to go back to sub menu Perimeter…….

Figure 10 Square Screen Output


54
Questions:
1. How many sets of switch structure were used in the program?
2. In the main menu selection, if the expression to be inputted is a number instead of
characters, which portion of the program needed to change?
3. What happens if the default statement in a switch structure is omitted?
4. Make pseudocode of the program.

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

55
Laboratory Exercise Rubric for Programming Logic and Design

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)
The documentation is The documentation The documentation
well written and clearly lacks some didn’t satisfy all the
Documentation explained all the information and some questions that were
(20%) questions given in the mistakes are found in given in the laboratory
laboratory exercise. the questions. exercise.
(20) (14) (7)

Total Score : ________________________

56
Big Picture in Focus:
ULO(2-c). To apply knowledge in program recursion structures such as
while loop, do/while loop and, for loop.

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.

1. Initialization. It sets the initialization value of the control variable, or sometimes


called counter, of the loop.
2. Condition. This will check the value of the source; the body of the loop is executed
only if the condition is true.
3. Updater. It updates or modifies the value of the counter or control variable either by
incrementing (e.g., x++) or decrementing (e.g., x--) so that the loop-continuation
condition eventually becomes false.

There are three types of loop: while, do-while and for a loop.

1. while loop – pre-test 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)
57
{
statements;
updater;
}

2. do-while loop – post-test loop

The do...while statement tests the loop-continuation condition after executing the loop's
body. Therefore, the loop body always executes at least once.

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.

3. for loop – pre-determined loop

The general form of the for repetition statement:

for (initialization ; condition ; increment or decrement)


{
statements;
}
.
All three expressions in a for statement are optional. If the condition is omitted, C++
assumes that the loop-continuation condition is always true, thus creating an infinite loop.
The initialization expression may be omitted if the program initializes the control variable
before the loop. The increment expression may be omitted if the program calculates the
increment with statements in the loop's body or if no increment is needed.

Repetition structures, or loops in while loop format generally come in two forms. The two
loops are:

58
1. Counter-controlled loop. A count-controlled repetition will exit after running a
certain number of times. The count is kept in a variable called an index or counter.
When the index reaches a certain value (the loop bound), the loop will end.

2. Sentinel-controlled loop. Sentinel-controlled repetition is sometimes called


indefinite repetition because it is not known in advance how many times the loop 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.

59
Let’s check and Analyze!

ULO (2-c): While loop – Task A

#include <iostream>
using namespace std;

int main()
{
char letter = 'a';

while (letter != 'x')


{
cout << "Please enter a letter" << endl;
cin >> letter;
cout << "The letter you entered is " << letter << endl;
} // end of while loop

return 0;
}

Questions (ULO 2-c Task A):


1. This program is not user-friendly. Run it a few times and explain why.
2. How would this code affect the execution of the program if the while loop is
replaced by a do-while loop? Try it and see.

ULO (2-c): While loop – Task B

// This program illustrates the use of a sentinel in a while loop.


// The user is asked for monthly rainfall totals until a sentinel
// value of -1 is entered. Then the total rainfall is displayed.

#include <iostream>
using namespace std;

int main()
{

60
// 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 read in the value for rain


// Fill in the code to start a while loop that iterates
// while rain does not equal -1

{
// 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;

// Fill in the code to read in the value for rain


} // end of while loop

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;
}

Question (ULO 2-c Task B)

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?

ULO (2-c): do-While loop – Task C

// 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
61
// the user selects item E from the menu.

#include <iostream>
#include <iomanip>
using namespace std;

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;

// Fill in the code to read in beverage

switch(beverage)

{
case 'a':
case 'A':
case 'b':
case 'B':
case 'c':
case 'C':
case 'd':

62
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
}

// 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
}

63
Questions (ULO 2-c Task C):
1. Fill in the indicated code to complete the above program. Then compile and run
the program several times with various inputs. Try all the possible relevant cases
and record your results. What did you realize from this exercise?
2. What do you think will happen if you do not enter A, B, C, D, or E? Try running
the program and inputting another letter.

ULO (2-c): for loop – Task D

// 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;
}
64
else
cout << "Invalid input - integer must be positive"
<< endl;
return 0;
}

Questions (ULO 2-c Task D):


1. Why is the typecast operator needed to compute the mean in the statement mean =
static_cast(float)(total)/value? What do you think will happen if it is removed? Modify
the code and try it. Record what happens. Make sure that you try both even and odd
cases. Now put static_cast<float> total back in the program.

2. What happens if you enter a float such as 4.58 instead of an integer for value? Try it
and record the results.

ULO (2-c): Nested for loop – Task E

// This program finds the average time spent programming by a student


// each day over a three-day period.

#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;

for(student = 1; student <= numStudents; student++)


{
total = 0;
for(day = 1; day <= 3; day++)
65
{
cout << "Please enter the number of hours ”
<<”worked by student "
<< student <<" on day "
<< day << "." ;
cin >>numHours;

total = total + numHours;


} // end of inner loop
average = total / 3;
cout << endl;
cout << "The average number of hours per “
<< ”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

How many students are there? 2

Please enter the number of hours worked by student 1 on day 1 4


Please enter the number of hours worked by student 1 on day 2 6
Please enter the number of hours worked by student 1 on day 3 5

The average number of hours per day spent programming by student 1 is 5

Please enter the number of hours worked by student 2 on day 1 9


Please enter the number of hours worked by student 2 on day 2 13
Please enter the number of hours worked by student 1 on day 3 6

The average number of hours per day spent programming by student 2 is 9

Questions (ULO 2-c Task E):

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

Student Generated Code Exercises

Problem 1:

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:

Choose 1, 2, 3, or 4 from the above menu


or -1 to exit the program 4

****************************************************
****************************************************
Please input the favorite beverage of person #2:

Choose 1, 2, 3, or 4 from the above menu


or -1 to exit the program 1

****************************************************
****************************************************
Please input the favorite beverage of person #3:

Choose 1, 2, 3, or 4 from the above menu


or -1 to exit the program 3

****************************************************
****************************************************

67
Please input the favorite beverage of person #4:

Choose 1, 2, 3, or 4 from the above menu or


-1 to exit the program 1
****************************************************
****************************************************
Please input the favorite beverage of person #5:

Choose 1, 2, 3, or 4 from the above menu


or -1 to exit the program 1

****************************************************
****************************************************
Please input the favorite beverage of person #6:

Choose 1, 2, 3, or 4 from the above menu


or -1 to exit the program -1

====================================================
====================================================
The total number of people surveyed is 5.
The results are as follows:

Beverage Number of Votes


****************************
Coffee 3
Green Tea 0
Soda 1
Juice 1

====================================================
====================================================

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
68
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:

Please input the time of fall in seconds : 2


Please input the height of the bridge in meters : 100

Time Falling (seconds) Distance Fallen (meters)


*******************************************************************
0 0
1 4.9
2 19.6
Sample Run 2:

Please input the time of fall in seconds : 4


Please input the height of the bridge in meters : 50

Time Falling (seconds) Distance Fallen (meters)


*********************************************************************
0 0
1 4.9
2 19.6
3 44.1
4 78.4
-------------------------------------------------------------------------------------------
…………Warning-Bad Data…………
The distance fallen exceeds the height of the bridge.
-------------------------------------------------------------------------------------------
Q&A List
Please write your queries on the table provided below:
Questions Answers

69
Laboratory Exercise Rubric for Programming Logic and Design

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)
The documentation is The documentation The documentation
well written and clearly lacks some didn’t satisfy all the
Documentation explained all the information and some questions that were
(20%) questions given in the mistakes are found in given in the laboratory
laboratory exercise. the questions. exercise.
(20) (14) (7)

Total Score : ________________________

70
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

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

71
programmer to enter the code once, in a function. Any section in the program can then call the
function to perform the required task.

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.

User-defined functions in C++ are classified into two categories:


 Value-returning functions – functions that have a return type. These functions return a
value of a specific data type using the return statement
 Void functions - functions that do not have a return type. These functions do not use a
return statement to return a value.

All value-returning functions, whether built-in or program-defined, perform a task and then
return precisely one value after the task is completed.

Syntax: Value –Returning Function

functionType funtionName(formal parameter list)


{
statements;
return statement;
}
In which; statements are usually declaration statements and/or executable statements.
In this syntax, functionType is the type of the value that the function returns. The
functionType is also called the data type or the return type of the value-returning function.
Moreover, statements enclosed between curly braces form the body of the function.

Syntax: Formal Parameter list


datatype identifier, datatype identifier;

72
Various parts of the function larger():

Consider the following statements:

double a = 13.00;
double b = 36.53;

cout <<” The larger of “ << a << “ and “ << b


<<” is “ << larger(a, b) << endl;

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

#include <iostream>
using namespace std;
double larger(double x, double y); // function declaration

int main()
{
double num; //variable to hold the current number
double max; //variable to hold the larger number
int count; // loop control variable
73
cout << “Enter 10 numbers.” << endl;
cin >> num;

max = num;

for (count = 1; count < 10; count++)


{
cin >> num;
max = larger(max, num);
} // end of loop

cout << “ The largest number is “ << max << endl;

return 0;
} // end main

double larger(double x, double y)


{
double max;
if ( x >=y )
max = x;
else
max = y;
return max;
}

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.

Syntax: Function Definition

void functionName (formal parameter list)


{
statements;
}

74
Two types of formal parameters:

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;

void fValueParameter (int num);

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;
}

void fValueParameter(int num)


{
cout << “ Inside the function fValueParameter, before changing, num = “
<< num << endl;
num = 15;
cout << “ In the function fValueParameter, after changing, num = “
<< num << endl;
}

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

If a formal parameter is a reference parameter, that is if you attach &(ampersand) after


the datatype, reference parameters can pass one or more values from a function and can
change the value of the actual parameter, because a reference parameter receives the address
(memory location) of the actual parameter. The & which is referred to as the address-of
operator, tells the computer to pass the variable’s address rather than copy of its contents.

Reference parameters are useful in three situations:


 When the value of the actual parameter needs to be changed.
 When you want to return more than one value from a function
 When passing the address would save the memory space and time relative to copying a
large amount of data.

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;
}

void getAge(int &inYears)


{
cout << “How old are you? “;
cin << inYears;
}

76
void display( int years)
{
cout << “ You are “ << years << “ years old.” << endl;
}

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

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.

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

Let’s check and Analyze!

ULO(3-a) Task A: (return type)


Code the IPO chart shown below. Display the Celsius temperature in fixed-point notation with
no decimal places.
Input Processing Output

Main function Processing items: none Celsius temperature


Algorithm:
Fahrenheit 1. Call getFahrenheit
temperature function to get the
Fahrenheit temperature
2. Call the calcCelsius to
calculate temperature;
pass the Fahrenheit
temperature
3. Display the Celsius
temperature

getFahrenheit Processing items: none Fahrenheit temperature


function
Algorithm:
Fahrenheit 1. Enter the Fahrenheit
temperature temperature
2. Return the Fahrenheit
temperature
calcCelsius
function Processing items: none Celsius temperature
Fahrenheit
temperature Algorithm:
1. Celsius temperature =
5.0 / 9.0 * (Fahrenheit
temperature – 32.0)
2. Return the Celsius
temperature
78
ULO(3-a) Task B: Write down your observations and learnings of the above activity.
Minimum of 50 words.

ULO(3-a) Task C: (void type, &, pass by reference)


Modify the code from Laboratory Task A. Change the getFahrenheit and calcCelsius
functions to void functions.

ULO(3-a) Task D: (Student Generated Code Exercises)


Create a program that calculates the average of entered n test scores. The
program should contain two value-returning programs (main and calcAverage) and two
void functions (getTestScores and displayAverage). The main function should call the
void getTestScores function to get the test scores. The test scores may contain a decimal
place. The main function then should call the value-returning calcAverage function to
calculate and return the average of the test scores on the screen. Display the average with
one decimal place. Use a sentinel value to end the program (the program will continue to
compute average of inputted test scores until a sentinel value is entered).

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:
Questions Answers

79
Laboratory Exercise Rubric for Programming

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)
The documentation is The documentation The documentation
well written and clearly lacks some didn’t satisfy all the
Documentation explained all the information and some questions that were
(20%) questions given in the mistakes are found in given in the laboratory
laboratory exercise. the questions. exercise.
(20) (14) (7)

80
Big Picture in Focus:
ULO 3-b. Create a program using single-dimension array

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

An array is a collection of variables of the same type and can be referred to by a common
name. An example of which is the scores for the quizzes of students.
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.

81
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].

Entering Data into a One-Dimensional Array

As you can with simple variable, you can use either an assignment statement or the
extraction operator to enter data into an array element.

How to use assignment statement to assign data to a one-dimensional array?

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

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

How to use the Extraction Operator to store data in a One-Dimensional Array

Syntax:

cin>>arrayName[subscript];

Example 1:
char letters[5];

cin>>letters[0]; // stores the user’s entry in the first element


// in the letters array
Example 2:

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

Displaying the contents of a one-dimensional 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;
83
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

Let’s Check and Let’s Analyze!


ULO(3-b) Task A: Develop a program that will sort the elements of a single dimension 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.

Figure 11. Sample Output of Sorting inputs


Questions:

84
1. What is the algorithm used to sort elements of array in ascending and descending
order?
2. How many integer arrays were used in this program?
3. Can this program be done with only 1 integer array being used? Explain your answer.
4. Explain how was the program able to determine the highest and lowest element.

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.

Q&A List
Write your questions on the table provided.
Questions Answers

85
Laboratory Exercise Rubric for Programming Logic and Design
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 lacks Source code is not
Specifications the complete details necessary details enough to run the
(30%) to run to program correctly.
the program run the program (10)
correctly. correctly.(20)
(30)
Source code is well Minor issues such Major issues are
Readability organized and easy to as variable naming, causing the codes
(10%) understand. variable utilization, to be not readable.
(10) etc. are observed. (3)
(6)
Source code is well Source code allows Source code does
Screen Output organized and easy to the required screen not meet the
(10%) understand. output to be required
displayed correctly screen output to
(10) with 1-3 errors be
found.(6) displayed
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
(20%) questions given in the some mistakes are were
laboratory exercise. found in the given in the
(20) questions. laboratory
(14) exercise.
(7)

86
Big Picture in Focus:
ULO(3-c) to create program using multi-dimensional arrays of numeric
and characters.

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.

Essential Knowledge

A two-dimensional array is a collection of a fixed number of components arranged in


rows and columns (two dimensions) similar to a spreadsheet, wherein all components are of
the same type. Each element in a two-dimensional array is identified by a unique combination
of two subscripts that the computer assigns to the element when the array is created. The
subscripts specify the element’s row and column positions in the array.
We refer each element in a two-dimensional array by the array’s name and the element’s
row and column subscripts, with the row subscript listed first and the column subscript listed
second. Like the single-dimension array introduced on the previous laboratory, the subscripts
start at 0 rather than at 1. For example, to refer to the element located in the first row, first
column in a two-dimensional array named scores, we use scores[0][0]. The element on the
last row and column is always one number less than the number of rows and columns in the
array.

Declaring and Initializing a Two-Dimensional Array

Syntax for declaring a two-dimensional array:

datatype arrayName[intExp][intExp2] = {{initialValues},


{initialValues},
87
…{initialValues}};

Example 1:
char grades[3][2] = {{‘C’, ‘A’}, {‘B’, ‘C’}, {‘D’, ‘B’}};

// declares and initializes a three-row, two-column char array


// named grades

Example 2:
double prices[6][5] = {2.0};

// declares and initializes a six-row, five-column double array named


// prices; the prices[0][0] element is initialized to 2.0; the other
// elements are initialized to 0.0

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.

Syntax for assigning data using assignment statement:

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];

for(row = 0; row < 4; row++)


for(column = 0; column < 3; column++)
orders[row[column] = 0;
// end of inner loop
// end of outer loop
// assigns the integer 0 to each element in the four-row, three-
// column orders array, row by row,; provides another means of
// initializing the array

88
Syntax for assigning data using extraction operator:

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

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)

Displaying the Contents of a Two-Dimensional Array

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;
89
while (column < 2)
{
while ( row< 3)
{
cout<< grades[row][column] <<endl;
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

Let’s Check and Let’s Analyze!

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.

Sample Screen Output

=================================
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: ____

90
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?
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 two-
dimensional 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

91
single entity (i.e student) are not a good idea. In a scenario like these arrays provide a better
way to store data.

Q&A List
If you have any questions, kindly write down on the table provided.
Questions Answers

92
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 lacks Source code is not
Specifications the complete details necessary details enough to run the
(30%) to run to program correctly.
the program run the program (10)
correctly. correctly.(20)
(30)
Source code is well Minor issues such Major issues are
Readability organized and easy to as variable naming, causing the codes
(10%) understand. variable utilization, to be not readable.
(10) etc. are observed. (3)
(6)
Source code is well Source code allows Source code does
Screen Output organized and easy to the required screen not meet the
(10%) understand. output to be required
displayed correctly screen output to
(10) with 1-3 errors be
found.(6) displayed
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
(20%) questions given in the some mistakes are were
laboratory exercise. found in the given in the
(20) questions. laboratory
(14) exercise.
(7)

93
Course prepared by:

Engr. Hanna Leah P. Angelia


Name of Course Facilitator/Faculty

Course reviewed by:

Randy E. Angelia, MSCpE, ME-ECE


Name of Program Head

Approved by:

Charlito L. Canesares,DEngg(ME)
Name of Dean

94

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy