0% found this document useful (0 votes)
2 views149 pages

Comp Prog Lectures

The document outlines the curriculum for CC 101: Computer Programming 1, covering fundamental computer concepts and programming skills essential for engineering students. It includes sections on computer technology, programming basics, algorithm design, and the C++ programming language, along with practical exercises. The course aims to equip students with the knowledge to understand and utilize technology effectively in their future careers.

Uploaded by

akim92320
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views149 pages

Comp Prog Lectures

The document outlines the curriculum for CC 101: Computer Programming 1, covering fundamental computer concepts and programming skills essential for engineering students. It includes sections on computer technology, programming basics, algorithm design, and the C++ programming language, along with practical exercises. The course aims to equip students with the knowledge to understand and utilize technology effectively in their future careers.

Uploaded by

akim92320
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 149

CC 101.

Computer Programming 1 SY 2017-2018

CC 101

______________________________________________________

COMPUTER PROGRAMMING 1

______________________________________________________

Table of Contents
I. Introduction to Computer Technology.....................................................................................................6
Concept of a Computer System...............................................................................................................6
What is a Computer?.........................................................................................................................10
Types of Computers...........................................................................................................................11
Features of a Computers....................................................................................................................12
Computer Hardware and Computer Software.......................................................................................14
Input Devices.....................................................................................................................................20
Processing Unit..................................................................................................................................21
Storage Devices.................................................................................................................................22
Output Devices..................................................................................................................................24
II. Introduction to Computer Programming...............................................................................................28
What is a Computer Program?...............................................................................................................28
What is Computer Programming?.........................................................................................................30
Process of Program Design....................................................................................................................33
III. Algorithm Analysis and Design...........................................................................................................35
Concept of Algorithms...........................................................................................................................35
Designing Algorithms using Pseudocodes.............................................................................................37

1|Page
CC 101. Computer Programming 1 SY 2017-2018

Algorithm Exercises 1.......................................................................................................................39


Algorithm Exercises 2.......................................................................................................................40
Designing Algorithms using Flowcharts...............................................................................................41
Algorithm Exercises 3.......................................................................................................................47
Algorithm Exercises 4.......................................................................................................................48
Algorithm Exercises 5.......................................................................................................................49
IV. Introduction to C++ Programming Language......................................................................................50
The Beginnings of C++ Language.........................................................................................................50
Programming Using C++ Language......................................................................................................51
Basic C++ Program Layout...................................................................................................................53
Basic Programming Terms.....................................................................................................................54
Programming Exercises 1..................................................................................................................56
Programming Exercises 2..................................................................................................................57
V. C++ Basics............................................................................................................................................58
Variables, Input/Output Streams, and Assignment Statements..............................................................58
Programming Exercises 3..................................................................................................................66
Programming Exercises 4..................................................................................................................67
Programming Exercises 5..................................................................................................................68
Variable Initializations and Constants...................................................................................................69
Programming Exercises 6..................................................................................................................73
Programming Exercises 7..................................................................................................................77
Programming Exercises 8..................................................................................................................78
Arithmetic Expressions and more Assignment Statements...................................................................79
Programming Exercises 9..................................................................................................................82
Programming Exercises 10................................................................................................................83
Programming Exercises 11................................................................................................................84
VI. CONTROL STRUCTURES (SELECTION)......................................................................................85
1. If...statement......................................................................................................................................87
Syntax of If statement:.......................................................................................................................87
2. If...else statement...............................................................................................................................90
Syntax of If...else statement...............................................................................................................90
2.1 Logical operators.................................................................................................................................93
2.2 Nested if...else statement (if...else if....else Statement)...................................................................96
Syntax of nested if...else statement....................................................................................................96
Let’s have an example of nested if else statement.............................................................................97
VII. Repetitive Control Statements..........................................................................................................108
2|Page
CC 101. Computer Programming 1 SY 2017-2018

Repetitive Control Structures..............................................................................................................108


The first repetitive statement is the while loop statement....................................................................110
Another repetitive statement is the do – while loop statement............................................................113
FOR LOOP STATEMENT..................................................................................................................116
The last repetitive statement is the for loop statement.........................................................................116
VIII. Functions.........................................................................................................................................123
Predefined Function.............................................................................................................................124
Programmer Defined Function............................................................................................................126
Types of Parameters.............................................................................................................................132
APPENDIX A......................................................................................................................................138
Reference List..................................................................................................................................13849

BACKGROUND OF THE MODULE (What is the module about?)

Welcome to your first computer class! As part of all engineering courses, this subject is the first
of the two parts in computer programming. This subject will provide you with the basic knowledge on
computer concepts as well as develop your skills in basic computer programming. This will also help
you understand the technology better and its use in the society and in the profession of your choice.

The basic knowledge and skills in computer technology and programming have become some of
the vital roles in creating competitive leaders of society. The society itself has transformed to adapt to
the changes in technology. One of such recent developments in technology is the use of the social
networking media such as Facebook, Twitter, Instagram, and others. Now, you are able to interact and
collaborate with other individuals despite the cultural differences and geographical distances.

The skills and knowledge in the use of this technology will not only help you communicate
better amongst your social circle but will also help you professionally in the future. The businesses and
professional industries have incorporated technology into their processes. Technology in the industry
has helped create a more productive and efficient environment. These fields in the industry will need
people like you who are capable and has the capacity to manage their processes with the use of
technology.

Moreover, the skills that you will gain in computer programming will place you one step ahead
over your peers in the industry. As future engineering graduates of WMSU, you will not only be users of
technology but you can also be one of the creators and developers of future innovations in technology.
Instead of using apps in Facebook, you can be the one to create such apps which people might use in
their work or just purely entertainment.

This subject will build the foundation of your basic computer technology knowledge and
programming skills. This manual, as part of the subject, will be your guide throughout the topics and
exercises that will be covered for this semester. For each section, you will be provided with a list of
3|Page
CC 101. Computer Programming 1 SY 2017-2018

topics and objectives. Make sure that at the end each section, you are able to meet the objectives
through the exercises given. This will help you to be ready for the succeeding topics. Your instructor will
also facilitate your learning throughout the entire subject.

So, enjoy and have fun learning!

OBJECTIVES OF THE MODULE

At the end of this course, the student should be able to:

1. Demonstrate understanding of the concept of computer system


2. Identify the basic components of a computer system
3. Learn the components in problem solving
4. Apply principles in procedural programming
5. Explore the strategies in problem solving in relation to procedural programming
6. Analyze problems and design algorithms to solve problems
7. Implement algorithms in a programming language
8. Apply basic language syntax and basic principles.
9. Write a programming project integrating the concepts and principles learned in this course.

4|Page
CC 101. Computer Programming 1 SY 2017-2018

I. Introduction to Computer Technology

Learning Outcomes/Objectives:

At the end of this section, you should be able to:

1. Describe the basic features of computers


2. Differentiate between hardware and software
3. Identify the different components of a computer system
4. Differentiate between input and output devices

Topic Outline:

1. Concept of a Computer System


a. What is a Computer?
b. Types of Computers
c. Features of a Computer
2. Computer Hardware and Computer Software
3. Hardware Components of a Computer
a. Input Devices
b. Processing Unit
c. Storage Devices
d. Output Devices

Concept of a Computer System

5|Page
CC 101. Computer Programming 1 SY 2017-2018

Computers, nowadays, have become a common device at work, school and at home. You might already
have a general knowledge of what a computer is. But have you ever used a computer? If you answered yes,
that’s great! You have a good start. If you answered no, do not worry. You might not know it yet, but maybe all
along you already have a computer right at your fingertips!

One of the most popular innovations that man has ever built is the computer. You might have watched a
movie or a show in TV where robots walk around like humans? Or maybe humans are almost like robots, like Iron
Man? Well, in reality, there are already robots developed but it doesn’t have its own intelligence yet to be like us.
For now, it is only limited to the imagination of the movie creators of what a possible future will be like. But you
will never know. Some of the technology that we have now, like your mobile phone, is only a possible future
decades or centuries ago.

The robots might be so advanced, but its development comes from the same basic concept of computer
technology that we have now. From the personal desktop computers, the computer technology has evolved to a
lot of other innovations like laptops, mobile phones, smart phones, tablets, and the like. These innovations in
technology have made most of human’s work easier and definitely, faster!

Try This!

Consider the devices below. Pair with a classmate and look for these devices around you, at
the computer laboratory, internet cafes, just at your friend’s house, or maybe at your own
home. Identify the parts that you can see from these devices and compare the different parts.
Identify some of the common parts between the devices. Also take note of the uses of these
devices in your daily life.

Figure 1.1a Figure 1.1b Figure 1.1c


A calculator A mobile phone A desktop computer

6|Page
CC 101. Computer Programming 1 SY 2017-2018

Think Ahead!

1. Provide the details below by answering each question and identifying what is being asked. Fill-out your
answers for each of these devices.

Device Details Calculators Mobile Phones Desktop Computers


What are the major
functions of these
devices? You can write at
most three (3) functions.

Which part(s) of the


device do you use to
enter data? NOTE: Data
can be text, sound,
image, or video.

Which part(s) of the


device do you use to
display or output data?

Which part(s) of the


device is used to process
the data you entered?

Which part(s) of the


7|Page
CC 101. Computer Programming 1 SY 2017-2018

Device Details Calculators Mobile Phones Desktop Computers


device is used to store
your data?

2. Identify five (5) advantages of using these devices in our daily lives?

SN ADVANTAGES

You may not own yourself any or all of these devices but you were able to identify its parts as well as its
advantages in the world that we live in. Congratulations! You have taken another step towards being techno-
savvy!

8|Page
CC 101. Computer Programming 1 SY 2017-2018

Think About This!

The use of these devices has greatly affected how people do their tasks. You might know how to
compute using pen and paper, but the calculator makes it easier to compute bigger numbers and faster. You
might go to a friend’s house and tell him/her the latest news but text messaging or calling using mobile phones
makes it more convenient. Any employee in a company can create their documents and store it manually in a
cabinet somewhere, but the creation, editing, and retrieval using a personal computer not only makes it faster, it
also makes management of files hassle-free and almost error-free.

What is a Computer?

So, what exactly is a computer? A computer is a collection of electronic devices operating under a set of
instructions stored in its own memory. It accepts data (Input), manipulates the data (Process), and outputs its
results (Output), and stores these results for future use (Storage) (Discovering Computers, 2002).

Figure 1.2 below illustrates the general tasks of a computer. The arrow between process and storage
means that results can be directly stored by the computer without displaying it to the user. Just think of IPOS, i.e.
Input, Process, Output, and Storage.

Figure 1.2 IPOS: Tasks of a Computer

In the simplest sense, a calculator as well as a mobile phone may be considered as a simple computer.
You enter your data into the keypad, the device will process your data, and a result will be displayed in the small
screen. For some calculators, you can even save your previous computations. Just exactly what we have
mentioned before, computers at your own fingertips!

However, the term “computer” is now commonly associated with desktop or personal computers (PC).
These are the type of computers that you see inside an internet café. With this, you can enter data in different
formats such as texts, images, sounds, or videos… it can process large amount of data… it can display outputs in
different formats as well… and it can store up huge data from megabytes (MB), to gigabytes (GB), to terabytes
(TB). Some of the new generation computers have also the same capabilities or even better but comes in small
packages like laptops and tablets.

9|Page
CC 101. Computer Programming 1 SY 2017-2018

Types of Computers

In general, computers can come in different sizes depending on its specifications. It could come in a form
of a wristwatch or as big as the size of classrooms or maybe even as big as a building. It could also be used for
different purposes. We could use PCs for personal use or supercomputers for big science research.

Computers can be categorized based on their operations and specifications. Specifications include its
size, speed of its computations, and the storage capacity. Figure 1.3 below shows the different categories or
types of computers.

Figure 1.3 Types of Computers (Computer Basics, 2009)

The following are the different types of computers (Fabien, 1999):

 Analog Computers – These are computing devices that use analog signals that are represented
as a continuous range of values. It generally deals with physical variables such as voltage,
pressure, temperature, speed, etc. You can see some of these devices at research institutes,
hospitals, and flight centers.

 Digital Computers – These are computing devices that use electrical inputs, ON or OFF. With
these devices data are represented by 0s (OFF) and 1s (ON). Digital computers can get more
accurate and faster results. It is best suited for solving complex problems in engineering and
technology. The most popular example of this type of computer is the PC.

o Super Computers – These computers are the best, in terms of processing capacity, which
means it is the fastest type of computer available. It can process about billions of
instructions per second. However, this is also the most expensive. These are mainly used
for complex scientific simulations and calculations like stock analysis and weather
forecasting.

o Mainframe Computers – These computers are also considered high-speed computers


which can process about millions of instructions per second. Just like a super computer,
it is also expensive. It is mainly used for the applications in banking, airlines, and
railways.

o Mini Computers – These computers have lower speed than mainframes and also less
expensive. Sometimes it is considered as a small-scale mainframe. In general, it is also
capable of supporting multiprocessing system for about 200 users. It is mostly used as

10 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

servers for some major business applications.

o Micro Computers – These are the most common type of computers used today. The
invention of single chip processors (CPU) creates cheaper but powerful microcomputers.
The most widely used amongst microcomputers are the desktop computers or PC. Other
devices such as laptops, handheld devices like tablets and personal data assistants (PDA)
also belong to this type.

 Hybrid Computers – These computers are very unique because they combine the operations of
analog and digital computers. They operate by using digital-to-analog converter and analog-to-
digital converter that will transform the data into a more suitable form for either type of
computation. These devices are mainly used for specialized task. An example of this is the
hospital’s ICU. The device measures the patient’s temperature, blood pressure, and other vital
signs. These data are converted into numbers using the digital components of the device so that
medical personnel will be able to monitor the values and be able to send signal if there are
abnormal values.

Features of a Computers

In whichever type, size, or configuration the computers may have, there’s no doubt that it is able to make
some complicated tasks simple. In general, it makes most of human’s tasks faster than any other tool available. In
the previous activity, you have listed down some of the advantages that the use of computers has contributed
into our daily lives. Here are some of the features that made all these advantages possible:

 Speed – As we have already mentioned before, computers work at a very high speed. We are
talking thousand (milliseconds), millions (microseconds), and billions (nanoseconds) of
instructions per second. Technically, it can read a book in a bat of an eyelash.

 Accuracy – Not only are computers fast, it is also accurate, not unless the user (you) gives a
wrong data or instruction. In this sense, computers are 100% accurate.

 Consistency – Unlike humans, computers can work efficiently continuously for many hours
without taking a rest. It also maintains its speed and accuracy. As long as it has power, it will not
stop working out of tiredness or fatigue.

 Versatile – Computers can do a variety of tasks from complex science simulations to simple
computations like playing your favourite games. It is used in variety of fields and industry.

 Storage – Computer can store large amount of data. Imagine the stacks of files and documents in
the office cabinets. The entire files and documents in your office can be stored in a single flash
drive which you can carry with you in your pockets.

 Reliability – Since computers work fast, accurate, and consistent, your data and other works may
be easily accessible for future use. You can be assured that it will be available for you when you
need it.

11 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Things To Do!

Now that you were able to know the characteristics of computers, do your research and provide actual
examples of the different types of computers. Note that supercomputers and mainframes are grouped as one,
and minicomputers and microcomputers for the other group. List down five (5) examples for each group and
identify where the computer is used or applied.

Examples of Super Computers or Mainframes:

SN Super Computers or Mainframes Application

Examples of Mini Computers and Micro Computers:

SN Mini Computers or Micro Computers Application

12 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Computer Hardware and Computer Software

In the previous activity, you were able to list down some of the parts of computer devices and its major
functions. We also mentioned the different types of computers based on their size, processing speed, and
storage. With these, you were able to see both the physical components of computers as well as the application
component through the functions which it is used for. In computer terms, these components of computers are
called the hardware and software.

Try This!

Remember the previous activity? This time consider only the desktop computer and mobile
phone. Aside from the different parts and components that you have seen in these 2 devices,
also look at the applications that are used for these devices.

Think Ahead!

Can you identify which are hardware and software components? Can you differentiate one from the
other? In the table below, list down the parts of the devices under the Hardware column and the applications
used for the devices under Software column. List as much items as you want.

Hardware Software

Check if you were able to identify clearly the hardware from the software components by referring to the
descriptions on the next page. If you have some doubts in your list, consult with your instructor.

13 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think About This!

A computer will be useless without either one of these components: Hardware and Software. The
hardware consists of the “hard” components of the computer, that is, the electronic or mechanical part of the
computer. So, if you listed the physical parts or devices that you have seen, then, you are on the right track!
Hardware is further divided into smaller components, that is, input and output devices, processing units, and
storage devices (see section on Hardware Components of a Computer).

On the other hand, the software consists of the “soft” components which are also called programs.
These are the applications that you use to do your work or task. These programs are also a set of instructions
that you feed into the computer in which the computer works on. You may refer What is a Computer Program?
section for more details. If you were able to list on some of these applications, you are doing a great job!

There are three (3) types of software, namely, System Software, Application Software, and Program
Software.

 System software are programs that control and maintain the operations of the computer and its devices.
It includes all operating systems, such as Windows OS, Ubuntu, Linux, and Mac OS, and utility programs,
such as computer management.

 Application software are programs that perform specific tasks for the user. It includes application to
create and manage word or text documents, spreadsheets, and presentations such as Microsoft Office
and Open Office. Web browsers, such as Chrome, Mozilla and Internet Explorer, and games are also
considered as application software.

 Program software are also called programming languages or development tools. These are programs
used to create other programs or applications. It includes Java, C#, PHP, and C++, among others. For this
subject, you are going to use the program software, C++ programming language, to create your own
programs.

Try to review the applications that you have listed as software. Were you able to identify all types of
software? Which type have you identified the most? Which type have you identified the least or maybe have not
identified at all? You can explore the devices more to look for more of these types of applications.

From the definitions of hardware and software, we can conclude that for a device to be considered as a
computer, it must have the hardware and software components. Software cannot run on itself. It needs a
hardware where you place or install the software. Also, the hardware cannot run on itself. Without the software
installed, it would just be another matter that occupies space.

In a sense, a computer can be likened to a human being, the physical body as hardware, the thoughts,
ideas, and feelings as software. Can you already imagine robots as classmates? Although a possible future, it will
take more complex and extensive artificial intelligence as well as high-end innovations in electronic devices to
create just that. Think: the processing speed and storage of supercomputers with a hundred times smaller than
microcomputer chips. With these, you can probably create robots that fly!

14 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Things To Do!

Based on the list of software that you have listed from the previous activity, identify what type of
software it is and its use or function. Identify three (3) examples for each type of software. Use the tables below.

Examples Application Software:

SN Application Software Function / Use

Examples of System Software:

SN System Software Function / Use

Examples of Program Software:

SN Program Software Function / Use

15 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Components of Computer Hardware

We know by now that computers accept data, process them into information, produce results, and store
these results for future use. For each of this task, a hardware component is needed. The components of
computer hardware are divided into:

 Input Devices
 Processing Unit
 Storage Devices
 Output Devices

How much do you know about each of these components? Can you identify which devices you have
listed belong to which component? Try the activity below to determine if your assumptions are correct.

Try This!

Consider the devices below. Identify and group these devices according to the
different components of computer hardware, that is, input devices, output devices,
processing unit, and storage devices. You can also include the list of devices that you
have identified in the previous activities (in case these are not present in the devices
given below) and also group them accordingly.

Mouse
Web Camera Microphone
Flat Screen Monitor
Printer

Keyboard
USB Flash Drive
Central Compact Disc
Speakers
Processing Unit

Figure 1.4 Collections of Computer Hardware Devices

16 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think Ahead!

1. Based on the groupings that you have created given the devices in Figure 1.4, list down the devices for
each group using the table below.

INPUT DEVICES OUTPUT DEVICES PROCESSING UNIT STORAGE DEVICES

2. Are there other devices, which you have identified from the previous activity, that are not included in
Figure 1.4? If yes, list these devices under each component where they belong.

There may still be other devices that you have not encountered before that also belongs to one of these
components. Some of these devices may differ in form depending on the type of computer you are using. For
instance, a mouse for desktop computers is equivalent to the touchpad for laptop computers.

Let’s explore more on some of these devices and how they form in a computer system.

17 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think About This!

Throughout this section, we have been discussing about the different devices and components to be able
to better understand computer technologies. In figure 1.2, we identified the different tasks of a computer. And
for each of this task, an equivalent classification of hardware device is used. Figure 1.5 below shows different
hardware components and the flow of data between devices. Although, these two figures are similar, they differ
in some areas. Can you spot the difference of this figure and Figure 1.2?

Input Process

Key: Data flow


Storage
Devices
Figure 1.5 Components of Computer Hardware (Hardware of Personal Computers, 2007)

The main difference is that the figure above describes the data flow between devices while the previous
figure determines the normal flow of tasks done by the computer. In summary, the figure above indicates the
flow of data rather than the flow of tasks. You can also note from Figure 1.5 that the flow of data from input or
storage devices always passes through the processing unit before it is either sent to the output device or stored
in the storage device.

In the first activity, we considered both a mobile phone and desktop computer as a type of computer.
Consider the figures below; try to compare the hardware components of these two devices.

Camera System Unit that


Memory contains the CPU and LCD
Screen
Card hard disk Monitor
Display
inside
this side
slot Inside: a SIM
Speakers card and an
on this embedded
side memory and
processor

Keypad
Microphone
Keyboard Mouse
Figure 1.6a Hardware Components Figure 1.6b Hardware Components of
of Mobile Phones Desktop Computers

18 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Although, mobile phones are especially designed for communications, some of its components are
similar or have equivalent components for desktop computers. For instance, keypads to keyboards and screen
displays to monitors. The major difference between the hardware components of these devices is that for mobile
phones, everything is compact and package as one device while in desktop computers, the hardware are
separated and are only connected by wires. This makes mobile phones and other handheld devices, such as
tablets and laptops more portable than desktop devices. Now, let’s take a look into more detail on some of these
devices for each of the hardware components.

Input Devices

Input devices are any peripheral device that is used to provide data in a form of instructions to the
computer. Data can be in a form of keystrokes, mouse clicks, touch screens, barcodes, sounds, images, and
videos, among others. The table below are some of these input devices:

Table 1.1 Common Input Devices


Input Devices Description
Keyboard It is the oldest and most widely used among the input
devices. It contains keys that represent numbers, texts, and
other symbols. A key press or keystroke or a combination of
keys will send the signal to the system unit that will be
equivalent to a character or command. Keyboards are
connected through wire, but nowadays, there are already
wireless keyboards that use Bluetooth technology to send
signal from keystrokes.

Mouse It is a pointing device that detects movement relative to the


flat surface where it is placed. A click on the mouse or
movement on the trackball sends signal to the system unit.
An equivalent arrow (pointer) represents the position on the
screen. The mouse is used to control this pointer by pointing,
clicking, double clicking and dragging objects across the
screen. A trackball is also a different variety of a mouse.
Microphone It is an acoustic electronic sensor device that converts sound
into electronic signals. It is used to record sound or to issue
commands using voice recognition software. In most cases,
you can also find microphone in headsets. Headsets already
contain a microphone and speakers for both ears. This makes
it more handy for users.

Joysticks It is similar to mouse in terms of controlling components in


the screen and navigation. This device is mainly used for
gaming purposes. It contains stick levers and buttons to
control the different characters in the game you are playing.
Joysticks are usually included in playstations but not desktop
computers. However, with the appropriate port, this device
can also be used in your PC.

Image Scanners It is used to analyze photographs, text documents,


19 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Input Devices Description


handwritten documents or any other object and convert them
as digital images. These image files become virtual copies of
the hardcopy photos or documents which can be stored,
make copies, or even edited. Image files have multiple
formats such as JPEG, PNG, GIF, and BMP file formats.

Web Camera
It is used as a real-time camera that reads in images through
its lens. It is mostly used to transmit real-time images in the
Internet. It is also used to capture images converted as image
files or record videos converted into video files. Video files
also have multiple formats such as AVI, WMV, MPEG, and
MP4 file formats.

Graphic Tablets
It is used for graphic design and animation. It consists of a
touch sensitive screen that acts as sensor, which sends signals
to the system unit. It also comes with a pen-like device, called
stylus. Using a stylus on this device, allows you to draw
images like you are writing or drawing on a paper. The
technology used for this device is greatly similar to the
touchscreen technology used in most smart phones and
tablets.
Barcode Reader
It is an input device that converts a pattern of patterned bars
into numbers. Each pattern is assigned an equivalent number
value. This is mainly used in business like supermarkets and
stores to quickly input product codes and other product
information. It uses similar technology with that of image
scanners.

This list of input devices is just some of the most common input devices available. The list does not in -
clude input devices that are already embedded into the main device, for instance, touchpads on laptops that
have same function as a mouse device. Another example is the TV tuner which is installed as cards in the system
unit. This device detects TV signals so that you can use your computers as television sets. Your ordinary camera
or video camera can also be used as input devices. There are still other input devices in the market that are wait -
ing for you to be explored.

Processing Unit

As you can see in Figure 1.5, every data passes through the processing unit. But what is a processing
unit? A processing unit in digital computers is called the central processing unit (CPU). The CPU is also known as
the “brain” of the computer. It is responsible in interpreting program instructions as well as processing data.
Figure 1.7 is an image of a chipset of a CPU (image size varies from actual size).
One of the key features of computers that were

20 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

mentioned before is the speed. Although, all computers have processing units, they vary in the time it takes for
the unit to process data. For instance, because supercomputers handle more complex applications, it needs a
very high speed processing unit, or else it might take ages to produce the desired output. Similarly, in desktop
and other personal computers, you need to consider the speed depending on your purpose. If you plan to use
your computer for animation, programming, or role-playing games then you need a higher processing speed
than maybe using it for document processing.

How do you determine the speed of the CPU?

There are two (2) factors that determine the speed of CPUs: the clock frequency (in MHz or GHz) and
amount of cache memory (in MB or GB). The clock frequency pertains to the number of instructions it process
per second while the cache memory is the amount of instructions it can hold. Take for instance, Intel Atom CPU
N475 model. It has a clock frequency of 1.83GHz and 2GB of memory cache. The higher the value of the clock
frequency and cache memory, the faster is the CPU. Most CPU nowadays are already in GHz (gigahertz or billions
of instructions per second) and GB (gigabytes or billions of bytes, i.e. group of bits of information).

Where can you find the CPU?

The CPU is not installed separately just like your input or


output devices. It is embedded in the system unit which contains
the motherboard. The motherboard contains the CPU, main
memory, and some other components. When you purchase a
computer the motherboard is already included in the system
unit.

The motherboard also contains slots for additional


memory and for input and output cards, such as sound cards and
video cards. Your input and output devices must be able to
communicate with your central processing unit. These cards
become an interface or bridge between the processing unit and Figure 1.7 Central Processing Unit
input and output devices. It converts the signals sent by input or Chipset
storage devices to the processing unit. And it also converts data from the processing unit into signals to be sent
to the storage or output devices.

Storage Devices

Another key feature of computers is its storage. There are two things that you should know about
computer storage: storage medium and storage devices or drives. The storage medium is the physical media
that holds data, instructions, and information for future use while storage devices record and retrieve data from
and to the storage medium (Discovering Computers, 2002). It also somehow acts as input to the processing unit
because it transfers date to it (see Figure 1.8).

Storage Medium

There are different types of storage medium for different purposes. The figure below shows the types or
classifications of storage medium.

21 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Figure 1.8 Classifications of Storage Devices (Hardware of Personal Computers, 2007)

The following are descriptions for each classification of storage device:

 Primary Storage – This is the storage that is directly accessible to the CPU of a computer without
any input/output channel. This is where currently used or active data is stored. The following are
different types of primary storages:

o Read-Only Memory – Data stored in this memory cannot be modified, hence, it is termed
as “read-only”. Data stored in this memory are standard or programmed instructions
created by manufacturers. ROM is non-volatile, that is, data remains the same even after
switching off the computer.

Figure 1.9 Read-Only Memory Chips


o Random-Access Memory – It consists of integrated circuits that allowed the stored data
to be accessed at any order, hence, it is termed as “random”. Data stored in this memory
are temporary (or volatile), that is, all data stored will lose after computer is switched off.

 Secondary Storage – This is the storage


that is not directly accessible to the
CPU. It needs input/output channels for it to access the processing unit. Data stored in this
device are not currently in active use. Since it is not directly accessible to CPU, it is slower than
the primary storage but it has a higher storage capacity. Examples of secondary storages are hard
disks (included in the system unit), USB flash drives, memory cards, and compact discs (see

22 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Figure 1.11). Data in these storages are non-volatile. So, whatever you saved in this type storage
will be there even if you switch off the computer.

Figure 1.11 Sample Secondary Storages

Storage Devices

The most commonly used storage device is the hard disk drive and CD-ROM or CD-RW drives. Hard disk
contains plotters where data is stored. These plotters are enclosed in a disk drive which reads and records data
into the plotters or disks. Compact Disc – Read-Only Memory (CD-ROM) drives read data from compact discs
which usually contain music or movie files. While Compact Disc – Re-Writable (CD-RW) drives record data into
compact discs. Nowadays, most of these drives are also compatible for DVDs. Figure 1.12 shows the different
kinds of storage devices.

Figure 1.12 Sample Storage


Devices
Output Devices

Output devices are any peripheral devices that are used to display or output information after data is
processed. The output or information is displayed in the form humans can understand. These outputs can be in a
form of image, video, or text display and sound, among others. The table below are some of these output
devices:

Table 1.2 Common Output Devices


Output Devices Description
Monitor It is the one of the most widely used of all output devices.
Monitors are included in almost any device from desktop
computers, laptops, tablets, to smart phones. It mainly
displays texts and images. From the processing unit, it
generates a temporary record, that is, any text or image
display will disappear once the power is turned off. Monitors
vary in screen size, resolution, and dot pitch.

The higher the resolution of the monitor, the higher the image
quality it produces. The two (2) major types of monitors are
Cathode Ray Tube (CRT) and Liquid Crystal Display (LCD). The

23 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Output Devices Description


figure on the left is an LCD type, sometimes also called a Flat
screen monitor. You can see both LCD and CRT monitors in
your computer lab rooms.

Printer It is an output device used to produce a hard copy of any


document both text and image. If monitors produce a
temporary record, printers produce a more permanent copy,
i.e. a copy printed on paper (hardcopy). There are many
different kinds of printers. The figure on the left is a type of
inkjet printer. This type of printer produces a copy by spraying
ink on paper. Some other types of printers include dot matrix
and laser printers.

Speakers It is an output device used to produce voice, music, and other


sounds processed and generated by the system unit. It is
connected through a sound card. Speakers can also be in a
form of earphones or headsets (earphone with an attached
microphone). Some other small devices like laptops, tablets,
and mobile phones already embed speakers into their device.
Speakers may also vary in their acoustic quality.

Projector It is an output device that produces text or image display by


projecting light into a surface. Monitors only display output
based on the size of its screen for mainly a single user.
Projectors, on the other hand, are designed to display output
for a larger group of audience. It is mainly used for group
presentations and meetings. Most of the projectors are quite
bulky, but nowadays, smaller and handier projectors are
becoming more popular.

Plotters It is an output device that is similar to printers, that is, it


produces hardcopy text or image documents. Plotters use
pens to draw straight lines that produce images, maps, charts,
and blueprints. Unlike printers which are mainly designed to
print outputs mainly in a standard paper document, plotters
are used for larger images. It is mainly used to print out
engineering designs or blueprints. Nowadays, it is commonly
used in graphics designs through tarpaulins and billboards.

24 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Just like some other components, there are other devices available that are not included in this list. And
some, similar to input devices, are already embedded into the device itself. There are already cameras that can
immediately print pictures. It is important to know all these devices to be able to determine the appropriate
technology to use. All these innovations are products of society’s demand to have a higher quality and a more
productive way of living.

Now, it’s time for you to be able to use these concepts and apply it into the real world.

Things To Do!

We know that computers are available everywhere and are used for different purposes. For this activity,
group yourselves into three (3). Visit a computer shop or computer store. Pick three (3) computers from their
display. You can choose a laptop, a PC or both.

1. List down the specifications of each computer using the table below.

Specifications Computer 1 Computer 2 Computer 3

Type (Laptop or PC)

Input Devices
(specify the details for
each input device)

Output Devices
(specify the details for
each input device)

Storage Media
25 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Specifications Computer 1 Computer 2 Computer 3


RAM
Hard disk
Others (specify
details)

Storage Devices
(specify the details for
each storage device)

Processing Unit
Processor Model

CPU (specify clock


frequency &
cache memory)
Software

System Software

Application
Software

Program Software

2. Based on the specifications that you have listed, which of the computers (1, 2, & 3) have the following:

a. contains a device that can create hardcopies : __________________________________


b. contains input devices other than mouse and keyboard : __________________________
c. with operating system other than Windows : ___________________________________
d. best monitor display : ____________________________________________________
e. highest primary storage capacity : ___________________________________________
f. highest secondary storage capacity: _________________________________________
g. fastest processing unit : __________________________________________________

26 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

II. Introduction to Computer Programming

Learning Outcomes/Objectives:

At the end of this section, you should be able to:

1. Describe what computer programs are.


2. Discuss what computer programming is and describe how computer programs are executed in a
computer.
3. Identify the basic steps in designing a program and demonstrate understanding by writing clear and
detailed instructions for a procedure.

Topic Outline:

1. What is a computer program


2. Understanding the concept of computer programming
3. Understanding how a program runs in a computer
4. Techniques in Program Design

What is a Computer Program?

In today's environment, the use of technology and computer applications is everywhere! Most of these
technologies are run by computer programs. Every single day, you encounter some of these computer programs.
Let’s have a look at some of the most common computer programs that are available right at your fingertips!

Try This!

Identify at least two (2) gadgets that you own personally or at home. It
could be your cellphone, mp3 player, or your desktop computer or laptop.
Think of some of the things that can be done with these devices.

27 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think Ahead!

Do you own a cellphone? If so, list at least two (2) things that you do with your cellphone?
____________________________________________________________________________________________
____________________________________________________________________________________________
____________________________________________________________________________________________
____________________________________________________________________________

List some of the applications that you use in your cellphones.


____________________________________________________________________________________________
____________________________________________________________________________________________
________________________________________________________________________________

Have you ever tried using desktop computers or laptops? If so, list at least two (2) things that you do with your
desktop computers or laptops.
____________________________________________________________________________________________
____________________________________________________________________________________________
________________________________________________________________________________
________________________________________________________________________________________

List some of the applications that you use in your desktop computers or laptops.
____________________________________________________________________________________________
____________________________________________________________________________________________
________________________________________________________________________________

What are the other devices that you have identified? List at least two (2) things that you do with these devices.
____________________________________________________________________________________________
____________________________________________________________________________________________
____________________________________________________________________________________________
____________________________________________________________________________
________________________________________________________________________________________

Most of the activities that you do with these devices like sending a text message, answering a call,
playing games, or checking your latest newsfeed in your Facebook account are made possible with the use of
computer programs. Your games, websites, including Facebook and Twitter and other applications that you use
are just simple examples of computer programs.

28 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think About This!

Computer programs consist of a sequence of instructions or steps that the computer interprets and
executes. A single application, like Facebook, can consist of several small computer programs. When you log-in,
for instance, based on your username / e-mail address, the program will check if you are a registered user. The
program will also verify if your username and password match based on the password that you also registered.

Ever played DOTA, HON, or Counter Strike? These role-playing and strategic games are also examples of
computer programs. The movements of the characters, change of environment and collection of items and
scores consist of sets of instructions or collection of smaller programs.

Looking at these applications, you might think that they are complicated and time-consuming and only
the geniuses can develop. Well, they may be true except for one thing: even YOU can develop a computer
program as big as Facebook or as fun as DOTA. But we will start with creating small programs first and progress
later on. So, put on your thinking caps! This module will help you create programs which can become big in the
future.

What is Computer Programming?

Have you ever wondered how a simple click of a mouse lets your favorite character in your game to
move? Or how the arrow keys allow Pac-man to move from up, down, left, & right? It is because programmers
(or at least the programs they designed) have written specific instructions for these behaviours to happen. A
computer program is composed of a sequence of instructions, and these instructions are written by the
programmers including YOU in the future.

For now, you should be able to realize that computers are only as good as the programs that have been
created for them. They only do what they are told to do. That is, they only behave based on how the computer
program behaves or were designed and programmed.

Try This!

Have you ever played a computer game or game using your phones? This is your
chance to get into your fun side! For this activity, play the game that you enjoy most.
Make sure that you have read the instructions and how you will get the best scores.

29 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think Ahead!

What is the name of the game?


________________________________________________________________________________________

List down the steps or instructions on how to play the game.


________________________________________________________________________________________
____________________________________________________________________________________________
____________________________________________________________________________________
____________________________________________________________________________________________
____________________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________________________________________
____________________________________________________________________________________________
________________________________________________________________________________
____________________________________________________________________________________________
____________________________________________________________________________________
________________________________________________________________________________________

How do you get a score?


____________________________________________________________________________________________
____________________________________________________________________________________
________________________________________________________________________________________

Did you enjoy the game? Did you get the highest score? You might observe that scores differ based on
how well you played the game. The program is written in such a way that you get higher scores on certain moves
or actions.

Think About This!

Computer programming is simply describing the steps or writing down the steps to do something. It is
like solving a puzzle or cooking a meal. However, since the computer does not understand English or any other
human language, a specific programming language is used.

The programmer writes the instructions (called “source codes”) in the computer using a programming
language. There are numerous programming languages that can be used. Some have specific targets and run
only on particular computers. The set of source codes are also called program codes.

30 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Figure 2.1 below shows the difference between instructions written in English language and written as
program code. Throughout this module, you will learn how to create source codes using C++ programming
language.

Steps in English language Program Code (in C++ language)


#include <iostream.h>
1 Start void main ( ) {
2 Output message “Hello World!” cout<<”Hello World!”;
3 End }

Figure 2.1 Sample Program Code


However, it should be noted that the only language that the computer understands is machine
language, which only contains the characters 0 (represents OFF) and 1 (represents ON).

After the programmer writes the source codes in high level language (in programs like C++, etc), the
language compiler (for this example, the C++ compiler) will interpret and translate the program code into
machine language (which is now what we call the executable file and typically with . exe extension).

Figure 2 illustrates how the program code is executed in the computer.

Figure 2.2 Concept of Running a Program (Rippe, 2009)

31 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Process of Program Design

You know by now that programs are just series of steps or instructions which you want the computer to
do. So, if you want to teach your friend how to bake a cake, you just have to give your friend the recipe or the set
of instructions on how to do it. This means anyone, including YOU, can write programs!

There are two (2) major phases that you go through when creating your program: (1) The Problem-
Solving Phase and (2) the Implementation Phase.

Figure 2.3 illustrates these phases of program design.

The Problem-Solving phase is where you define the problem and identify the sets of instructions on how
you are going to solve the problem. For the above example, the problem is baking a cake and the instruction is
the recipe. In this phase, you are going to create algorithms and flowcharts for the steps that you identified.

The Implementation Phase is where you convert your instructions to a series of source codes using a
programming language. For this course, we will be using C++ as our programming language.

For each phase, you have to do simulations or tests to be able to verify if you have successfully solved
the problem at hand.

Figure 2.3 Concept of Program Design

No matter what programming language you are going to use in the future, the solution or instruction
that you are going to create will be the same. Therefore, the key to creating a good program is to be able to write
specific and detailed sets of instructions that will be a clear solution to the problem at hand.

32 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Things To Do!

Let us exercise your skills in writing step-by-step instructions. Remember the process you go through
during enrolment for this semester? Write down a detailed step-by-step procedure of the enrolment process.
Note: Write the procedure as if you are giving instructions to incoming WMSU freshmen students.

Step No Instructions / Procedure


1
2
3
4
5
6
7
8
9
10
11
12

33 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

III. Algorithm Analysis and Design

Learning Outcomes/Objectives:

At the end of this module, you should be able to:

1. Create algorithms for solving problems using simple English.


2. Express simple algorithms in a pseudocode form.
3. Express simple algorithms using flowcharts
4. Analyze and simulate pseudocodes & flowcharts

Topic Outline:

1. Understanding the concepts of Algorithms


2. Writing Algorithms in Pseudocode format
3. Writing Algorithms in Flowchart format
4. Algorithm Simulation

Concepts of Algorithms

What comes to your mind when you hear the word “algorithm”? Robots? Mathematics? Science-fiction?
Did you know that algorithm exists every day in our lives? Signing into your Facebook or Twitter accounts…
changing the battery of your cellphones… ordering in a restaurant… or simply baking a cake. What is common
among all these? All of the things mentioned require us to follow a series of steps before we can accomplish
what we want to do. This sequence of steps to reach a goal or achieve a desired output is called an algorithm.

Try This!

Assuming you are the cashier in a grocery store and your customer orders 2 cartons of
milk worth Php90 each and 1 loaf of bread worth Php25. Your role now is to determine
the total amount that your customer needs to pay for the goods he wants to get.

34 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think Ahead!

What are the data or values needed to solve this problem?


_____________________________________________________
_____________________________________________________

Given the values, determine the steps to determine the output of this problem.

No. Steps
1
2
3
4
5
6

Now, you have just written your first algorithm! Isn’t it easy?

The data or variables that are needed and asked in the problem are the following:

Inputs: Price of milk, Price of bread, Number of cartons, Number of loaves of bread
Output: Total Amount

There are many ways to write the algorithm for the example given. Is your algorithm similar to the one below?

1 Input Price of milk = 90, Price of bread = 25


2 Input Number of cartons of milk = 2, Number of loaves of bread = 1
3 Compute Total Price of Milk = 90 * 2
4 Compute Total Price of Bread = 25 * 1
5 Compute Total Amount = Total Price of Milk + Total Price of Bread
6 Output Total Amount

If your steps are similar above, you are very close to creating a good algorithm! Good job!

35 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think About This!

Like the previous example, a typical algorithm has inputs, outputs, and a step-by-step process. Your
inputs are the values needed to solve the problem, and your outputs are the desired data or values. In algorithm
design, inputs are processed through a series of steps and an output is produced.

Input Process Output

Figure 3.1 Example of a Typical Algorithm

Algorithms can be written and expressed in different ways. In programming, an algorithm can be
described in the form of a pseudocode or a flowchart. Pseudocodes do not follow any particular computer
language and are written in simple English. Sometimes, they contain common mathematical expressions like =,
*, +, -, and others. Some statements will test a condition (if..then..else) and branch to a different part in the
algorithm. Flowchart, on the other hand, uses symbols in describing the steps. We first try to create algorithms in
simple English which is more familiar to you.

Designing Algorithms using Pseudocodes

Let’s say you are asked to write an algorithm for computing the area of the rectangle. First, identify the
needed input variables and expected output of this algorithm:

Inputs: length, width


Outputs: area of the rectangle

Below are the possible algorithms that you can create from this problem. Note that the words in bold
letters are the sets of variables either as inputs, outputs, or other computed values.

Algorithm 1:
inputs
1 Input length, width
process 2 Compute area = length * width
3 Output area
output

Algorithm 2: (you can further improve the algorithm by allowing the user to compute the area for another set of
values.)

36 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

1 Input length, width


2 Compute area = length * width
3 Output area
4 Message “Do you want to compute for another set of values? [Yes/No]”
5 Input answer additional input
For 6 If answer is “Yes”
repetition of 7 Go to Line 1
steps 8 Else
9 End of process

In order to check if the algorithm solves our problem, you can simulate or test the steps that you have
created. To simulate, you can assign actual values to the input variables and follow the series of steps that you
have outlined to see if your algorithm accomplishes what it is supposed to do.

Sample Simulation. Assume that the length and the width of the rectangle are 10 and 8, respectively.

Algorithm Simulation

1 Input length, width Input length = 10, width = 8


2 Compute area = length * width Compute area = 10 * 8 = 80
3 Output area Output 80

You can test this further with other values. To be able to write an effective algorithm for a program, identify
the following characteristics that a good pseudocode must have (Balci, et.al., n.d.):

1. Algorithms are well ordered.


2. Algorithms have unambiguous operations. Steps are clearly defined and leave no room for
misinterpretation.
3. Algorithms have effectively computable operations.
4. Algorithms produce results.

37 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Things To Do!

Algorithm Exercises 1

1. To enhance your knowledge in creating algorithms, group yourselves with 5 members for every
group formed. List each member’s scores from the last quiz. Write a general algorithm for finding the
average of the scores of five (5) individuals and output the computed average. After you write the
algorithm, test it with the scores that you listed as inputs.

No. Steps
1
2
3
4
5
6
7
8
9
10

2. Using the same algorithm, individually simulate the steps using a different set of values. Are the
results of your algorithm correct? If yes, then you have created a well-written algorithm. Good job! If
not, you can analyse the problem again and refer to your instructor for the correct answer.

38 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Algorithm Exercises 2

1. Write an algorithm that will compute for the area of a triangle given its base and height. The algorithm
must allow the user to compute for another set of data.

No. Steps
1
2
3
4
5
6
7
8
9
10

2. Simulate your algorithm using two (2) different measurements of triangles.

No. Triangle 1 Simulation Triangle 2 Simulation


1
2
3
4
5
6
7
8
9
10

39 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Designing Algorithms using Flowcharts

Did you know that symbols can also be used as instructions? Have you seen some signs on the streets
and roads? The name and numbers of the streets… the left & right arrow directs… etc. These signs are guides to
places where you want to go. Isn't it easy to have a map with you when you try to go to somewhere?
Applications like Google maps can even tell you how fast you can go to that place whether you will use a car, a
bus, or just simply walk. Using a map, you will know whether to go left or right.

From the previous section, you have learned how to create algorithms using pseudocodes. Now, just like
a map, you are going to use symbols to describe your instructions or algorithms.

Try This!

Review the scenario of the cashier in a grocery store. Also take note of the pseudocode that you
have created from that scenario. Using the symbols in Table 3.1, substitute your instructions with
the symbol it represent.

Table 3.1 Basic Symbols used in Flowchart


SYMBOLS DESCRIPTION
Start/End
The terminator symbol marks the starting or ending point of the
system. It usually contains the word "Start" or "End".
Action or Process
A box can represent a single step ("add two cups of flour"). A
step could also mean a computation for mathematical formula.
Input/Output
Represents material or information entering or leaving the
system, such as customer order (input) or a product (output).
Flow Line
Lines indicate the sequence of steps and the direction of flow. It
is used as a symbol to connect one symbol to the next.
Decision
A decision or branching point. This may include conditions like if
and if-else. The points in the diamond will represent the results
or decision of the condition (such as Yes/No) and which step it
will take next based on the decision.

40 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think Ahead!

1. Use the table below to draw up your flowchart. The pseudocode on the left is based on the previous
algorithm that we created. Draw the corresponding symbol for each line on the right column.
Note: The use of the terminator symbol is already included at the start and end of the algorithm.

Line No ALGORITHM (using Pseudocode) FLOWCHART SYMBOL

1 Start Start

2 Input Price of Milk, Price of Bread

Input Number of cartons, Number of


3
loaves of bread

4 Compute Total price of milk

5 Compute Total price of bread

6 Compute Total Amount

7 Output Total Amount

8 End End

41 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

2. Draw the final flowchart for the algorithm by connecting all the symbols using the flow line symbol.

YOUR FINAL FLOWCHART

Great! You have successfully created your first flowchart! Verify with your instructor if your flowchart is
similar to the equivalent flowchart for this algorithm.

42 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think About This!

From the previous activities, you have learned that algorithms can be written either using pseudocodes
or using symbols through flowcharts. Basically, a flowchart is just a graphical representation of an algorithm. You
can say that flowchart is also an algorithm, in graphical format.

In the previous flowchart, you have used symbols such as rectangles, oblongs, and rhombuses. These
symbols describe the various operations (or instructions) in your algorithm. These symbols are connected with
arrows to indicate the flow of data or operation from one instruction to the next.

Let's take the problem on computing for the area of a rectangle. You know that you can write your
algorithms in multiple ways. Below, you can see how each algorithm can also be designed using flowcharts.

Algorithm 1:

Line
Using Pseudocode Using Flowchart
No

1 Start

2 Input length, width

Compute area = length *


3
width

4 Output area

5 End

The above flowchart uses the three (3) most basic symbols in flowcharting. These symbols are mostly
present in any program or flowchart.

Algorithm 2: (using decision symbol)

43 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Line
Using Pseudocode Using Flowchart
No

1 Start

2 Input length, width

Compute area = length *


3
width

4 Output area

Message “Do you want to


compute for the area of
5
rectangle again?
[Yes/No]”

6 Input answer

7 If answer is “Yes”

8 Goto Line 2

9 Else

10 Goto Line 11

11 End

For this flowchart, we use the decision symbol to represent the if statement on line 7. The corners of
decision symbol can be used to place the possible flow information and data. In this example, the possible data
flow is either a Yes decision or No decision.

44 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Sample Simulation: Let us assume that we will compute for the area of two (2) rectangles. For the first
rectangle, the length and width is 10 and 8 respectively, and for the second rectangle, it is 15 and 10 respectively.
Since we are going to compute for the area twice (repetition), we will be using Algorithm 2.

Flowchart for Algorithm 2 Rectangle 1 Rectangle 2

Start ----

Input length = 10,


width = 8 Input length = 15, width = 10

Compute area = 10 * 8
Compute area = 15 * 10 = 150
= 80

Output 80 Output 150

Message “Do you want


Message “Do you want to
to compute for the area
compute for the area of
of rectangle again?
rectangle again? [Yes/No]”
[Yes/No]”

Input Yes Input No

Since answer is Yes,


Since answer is No, end this
input another set of
algorithm
values for Rectangle 2.

---- End

As you can see for the first rectangle (first computation), the program does not end yet; instead, you
repeat the inputs for the second rectangle (second computation). You can test this further with other set of
values or repeat the computation multiple times.

45 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Things To Do!

Algorithm Exercises 3

Now, let us test your skills in writing algorithms. Identify the inputs and outputs for each problem and
create the algorithm using pseudocode and flowchart.

Problem: Create an algorithm that computes for the student’s final grade using the formula below:

FINAL GRADE = 40% (Midterm Grade) + 60% (Final Grade)

Input/s: _____________________________
Output/s: ____________________________

Algorithm:

Line No Pseudocode Flowchart

Algorithm Exercises 4

Problem: Modify your flowchart on Algorithm Exercises 3 to allow repetitive computations for the student’s final
grade. Your new algorithm should allow computations for 1 or more students. Simulate the algorithm for 2
students with the following equivalent midterm and final term grades:

46 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Student Midterm Grade Final Term Grade


1 90 95
2 85 90

Algorithm:
Algorithm Simulation
Flowchart
Student 1 Student 2

47 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Algorithm Exercises 5

Problem: Modify your flowchart on Algorithm Exercises 4. This time, it should be able to determine if the
student passed or failed. The passing rate is 75 and above. You may also use the greater than (>) or less than (<)
operators for this condition. And it should also do computations for 1 or more students. Simulate the algorithm
for at least 2 students, one failed and one passed. Use your own sets of values.

Student Midterm Grade Final Term Grade


1
2

Algorithm:
Algorithm Simulation
Flowchart
Student 1 Student 2

IV. Introduction to C++ Programming Language

48 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Learning Outcomes/Objectives:

At the end of this section, you should be able to:

1. Write your first “Hello World!” program using C++ environment


2. Compile and run a program in C++
3. Create a simple C++ program based on a given problem

Topic Outline:

1. The Beginnings of C++ language


2. Programming using C++ Language
3. Basic Programming Terms
4. Layout of Simple C++ Program

The Beginnings of C++ Language

You know by now that programs are just made up of sets of instructions. However, the computer will
only understand your instructions if it is written in a programming language. Different programs can be written in
different programming languages.

The most popular programming languages include C++, Java, and C#, among others. Maybe these terms
sound a bit alien to you for now. In the field of computer science, these are common terms and soon will also be
common terms to you. For this subject, we are going to use C++ language.

C++ language is one of the most commonly used languages when learning the basics of programming. C+
+ was originated in C language, which was developed by Dennis Ritchie. In the early 80s, Bjarne Stroustrup from
Bell Labs began the development of the C++ language. Nowadays, C++ is used in different applications for
hardware platforms. Table 4.1 shows an overview of the C++ language and programming language, in general.

Table 4.1 Overview on the beginnings of programming languages and C++ Language
Year Milestone Overview
First programmable Charles Babbage, an English Mathematician and physical scien-
1873 computer tist, designed the first truly programmable computer. He was
then called “The father of Modern Computer”.
First Programmer Lady Ada Lovelace became the first programmer and developed
1953
the Ada language.
The Origin: C language Dennis Ritchie invented the C language and first implemented it
1973
on a DEC PDP – II that uses the Unix Operating System.
From C to C++ Language Bjarne Stroustrup developed the C++ language that is based on
1980
the C and another language called Simula.
1983 to Versions of C++ Language 1983 ANSI (American National Standard Institute) established a

49 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Year Milestone Overview


Then & Now committee to create an ANSI standard for C language called
Present Turbo C (later Turbo C++)
Microsoft also developed its version of the C++ called Visual C++

Programming Using C++ Language

Let’s go back at what you have learned when creating your algorithm. You know that an algorithm is just
a set of instructions or a series of steps. So, when you create your algorithm and you think of the series of steps
to solve the problem, you are actually thinking of the procedure. This is what we call procedural programming
(also known as structured programming).

C++ is actually a type of a structured programming language. Hence, it is very important that you know
how to write your algorithm, either in pseudocode or flowchart, before you write your program. These
instructions in your algorithm will already be equivalent to your program code, also known as your source code.

Try This!

In this activity, your instructor will introduce you to the C++ environment. You will be demonstrated how
to COMPILE and RUN your first program. For your first program, take note of the following steps:

1. Write the program code below in your first C++ file. NOTE: Do not anymore include the line
numbers. The numbers are only used to reference the line of codes in your program.

1 #include<iostream.h>
2
3 int main( )
4 {
5
6 cout<<”Hello, World!”;
7

2. Save your file as “HelloWorld.cpp”.


3. COMPILE your program. Consult your instructor when you encounter some errors.
4. RUN your program.
Think Ahead!

50 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

1. When you compiled your program, what message was displayed?


_____________________________________________________________________________________
_______________________________________________________________________________

2. Did you encounter some errors when you compiled? If so, what error message/s was displayed?
__________________________________________________________________________________-
_____________________________________________________________________________________
_____________________________________________________________________________________
____________________________________________________________________________

3. After you successfully run your program, what output message was displayed?
_____________________________________________________________________________________
_______________________________________________________________________________

Good job! You were now able to write your very first program! This time, you can do a little modification
to your program. Try to change “Hello World!” to “Hello, Philippines! Hello, World!”.

4. What is the new output message displayed?


_____________________________________________________________________________________
_______________________________________________________________________________

5. How about this, change “Hello, Philippines! Hello, World!” to “Hello, Philippines! \n Hello, World!”.
What is the difference between the previous output and the latest output message?
_____________________________________________________________________________________
_______________________________________________________________________________
6. Add the following line of codes after Line 6 cout<<”Hello, Word!”;

7 cout<<”This is my first C++ application”;

7. What is the new output message displayed?


_____________________________________________________________________________________
_______________________________________________________________________________

The “\n” is just one of the most common characters that you will be using when implementing your
programs. Any characters after “\n” will be written on the next line. Another way is to create another cout
statement.

As you can see, the output of your program clearly depends on what you write on it. So, if you write your
program incorrectly, then you will also get an incorrect output. We call this as GIGO or Garbage In, Garbage Out.

Hence, it is important to simulate first your algorithm, to check whether it is ready to be implemented in
C++. From now on, aside from creating algorithms, you will also be using the C++ environment, so start getting
comfortable with it! As for your first program, great job!

Think About This!

51 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

The Hello, World! program that you have created follows the basic structure of any C++ program code.
Table 4.2 below shows the basic layout of a C++ program and how your Hello, World! program fits into this
layout.

Table 4.2 Basic Layout of C++ Programs


Line
Basic C++ Program Layout Hello World! Program
No.
1 #include<iostream.h> #include<iostream.h>
2
This part is optional. For this program,
3 int main () int main ()
we did not use any variable, hence, no
4 { {
5 variable declarations;
variable declarations.
6
7 statement_1;
8 statement_2;
9 statement_3; cout<<”Hello, World!”;
10 …
11 last_statement; For this program, we only created one
12
(1) line of statement. You can have as
13 return 0; return 0;
many statements as you like
14 } }
depending on the program that you
are creating.

There are two (2) basic important things that you should be aware of when writing your program code.
First, C++ program is case sensitive. This means that the commands should follow the character cases properly.
For instance “int” in Line 3, should not be written as “Int” or “INT”. Changing the cases, lower case to upper case
or vice versa, will be equivalent to a program error.

Lastly, most of the line statements end with a semicolon (;). This marks the end of a step or a line of
instructions. A missing semicolon would also produce another program error. So, be careful. You don’t want to
crack your head in finding the error only because you missed a semicolon.

Basic C++ Program Layout

To understand the program layout better, the following discuss the different parts of the layout based on
the line numbers:

 Line 1 : include directive


o The C++ contains a series of libraries where reserved words (see Basic Programming
Terms) or commands are defined. The include directive tells the compiler where to find
information about certain items that are used in your program.
o Example: #include<iostream.h>
 The iostream is the name of the library that contains the definition of the
routines that handle input from the keyboard and output to the screen.
 The program included iostream because it contains the cout statement.

52 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

 Line 2 : variable declarations


o This is the part of the program where declarations or definitions of variables are made
(see Variables and Assignments).

 Line 3 : int main()


o int - indicates that the program returns a value with an integer data type (see Data
Types for more information).
o main () - indicates the start of the program or main function. The C++ always looks for
the main function at the start of any program.

 Lines 4 and 14 : { and }


o mark the beginning and end of the main() part of the program

 Lines 7 to 10 : program statements


o contain the equivalent codes or sets of instructions of your program.

 Line 12 : return 0
o also called the return statement.
o return 0 means that the program returns a zero value. Note: The value 0 can vary
depending on the function of the program (more of this on the Functions section of this
manual.)

NOTE: C++ language executes the program code line by line, the close brace (}) marks the end of the program.
Braces are also used in Flow of Control statements to indicate a start and end of a block of codes. Hence, you
might encounter multiple sets of braces in a single program. Just remember that they come in pairs, i.e.
beginning and end.

Basic Programming Terms

Before we proceed to the actual implementation of the functions and commands, we first have to take a
look at some of the terms used in programming languages.

o Reserved Words. These are words that are already used by the programming language (C++). These
words have special meaning to the language. Therefore, you cannot use reserved words as your variable
or identifier (see meaning of identifiers).

In our Hello, World! program, the reserved words are the following: #include, int, cout, and re-
turn.

o Identifiers. These are names used to reference variables, functions, labels, and various other objects that
you define in your program. In creating identifiers, you must consider the following:

• contains 1 to 32 characters
• first character must be a letter (a-z, A-Z) or an underscore (_)

53 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

• subsequent characters can be either letters (a-z, A-Z), numbers (0-9), or underscore (_)

Examples of valid identifiers: count, _player1, first_player

Examples of invalid identifiers: !count, player.1, first..player

NOTE: Again, C++ is case-sensitive, this means that lowercase characters are considered different from
their uppercase equivalents, that is, a is different from A and count is different from COUNT.

o Syntax. It is the format or structure on how source codes should be written. There are certain rules that
you should follow in writing your source codes for a particular function.

o Semantics. In order to understand the syntax, you always refer to the semantics. The semantics give
meaning or description to your syntax. It is important to take note of the semantics, so that you will un-
derstand the syntax better.

You will encounter different syntax and semantics once you already start using different com-
mands and functions.

Things To Do!

Programming Exercises 1

54 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

The algorithm below displays a given text. Create the equivalent C++ program code for this algorithm.

Algorithm C++ Program

1 Start
2 Output message “It’s more fun to
learn programming in using C++!”
3 End

What will be the output for this algorithm?

Program Output:

55 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercises 2

Create an algorithm, either using pseudocode or using flowchart that will output your name, course, and
motto in life. Write the equivalent C++ program for this algorithm. As your guide, see the sample output
below.

Sample Program Output:

Name: Bella Swan-Cullen


Course: BS Computer Science
Motto: Live life to the fullest!

Your Program:

Algorithm C++ Program

56 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

V. C++ Basics

Learning Outcomes/Objectives:

At the end of this section, you should be able to:

1. Use variables to store, manipulate, and retrieve data inputs.


2. Use different arithmetic operations and expressions in a C++ program.
3. Create a C++ program with computations based on a given problem.

Topic Outline:

1. Variable Declarations, Input/Output Streams, and Assignment Statements


2. Variable Initializations and Constants
3. Data Types
4. Arithmetic Expressions

Variables, Input/Output Streams, and Assignment Statements

Most of the programs, just like Facebook, require the user to input certain data or information before
you can log-in or before you can search people from your friend list. And just like our sample problem on the
area of a rectangle, most other programs require certain computations and validations. And besides, it would be
a boring program if it will only display what you just typed. Wouldn’t you agree?

Now, in order to be able to do some data entry and computations, you have to learn how to use variables
and assignment statements.

Try This!

Say you are in a money changer business. One of your customers wants
to convert a 100 US-dollar bill to Philippine pesos. Assuming that $1 =
PHP 41, how much will your customer receive in exchange for his 100
US-dollar bill?

57 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think Ahead!

1. What do you think are the inputs and outputs for this problem?

Input/s: ___________________________________
Output/s: _________________________________

2. Assign names to your inputs (input variables) and outputs (output variables). Using these variable
names, create a formula that will be able to covert US Dollar to Philippine Peso.

Input Variable/s: ___________________________________


Output Variable/s: ___________________________________
Formula: ___________________________________

Let us check if your variables are correct identifiers to be used in your program. The following questions
will determine if you have written a correct identifier or not:

• Does your variable name contain 1 to 32 characters?


• Is the first character of your variable name a letter (a-z, A-Z) or an underscore (_)?
• Are the subsequent characters (i.e. after the first character) in your variable name contain ei-
ther letters (a-z, A-Z), numbers (0-9), or underscore (_)?

If you answered “Yes” to all the questions above, then you can already use these variable names into
your program. Otherwise, you have to change your variable names to fit into these criteria.

3. Once you already have your variable names, create the equivalent algorithm for this problem. Your
algorithm must be able to produce similar to the sample outputs below.

Sample Output 1:

MONEY CONVERSION This is a sample


input. For your
algorithm, use the
Bill in US dollar ($): 1
input and output
In Philippine Peso (PHP): 41 variable names.

58 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Sample Output 2:

MONEY CONVERSION

Enter amount in US Dollar ($): 1

Equivalent in Philippine Peso (PHP): 41

Write your algorithm here:

MONEY CONVERSION

59 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

You know by now that there are multiple ways to create your algorithm. In your output messages, you
can even write the texts in your own language (Tagalog, Chavacano, Bisaya, etc.). If your algorithm is
similar to the table below, then, great job!

Line No Algorithm
1 START
2 Output message “MONEY CONVERSION”
3 Output message “Enter amount in US Dollar ($): ”
4 Input dollarAmount
5 Compute pesoAmount = dollarAmount * 41
6 Output message “Equivalent Amount in Philippine Peso (PhP): ”
7 Output pesoAmount
8 END

Think About This!

Are you ready to create programs that actually interact with the user? Right now, you have already
written algorithms that actually do this… but not yet an actual program. Most programs that you are going to
write will now contain the basic components: Inputs, Process, and Outputs. Let’s take a look at these
components on the Money Conversion algorithm.

OUTPUT STREAMS. On the previous activities, you created programs that display messages using the cout
statement. For this algorithm, you can use the cout statement to display the texts or messages.

cout statement: command used to display text on the screen or display the
value of a certain variable. It is used with the insertion operator, which is written
as <<, (two “less than” signs).

The table below shows the format on how you are going to use cout statements. The syntax shows the format,
while the semantics shows the meaning of the format.

Output Streams
To display a text:
cout<<”write text here”;
To display the value of the variable:
Syntax
cout<<”variable name”;
To display both value of the variable and text in one line:
cout<<”Value of data is ”<<variable name;
You can write the text that you want to display inside the quotations.
Semantics
variable_name: any declared variable

60 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Using the syntax for Lines 2 & 3, the equivalent program code may be written as
cout<<”MONEY CONVERSION\n”;
cout<<”Enter amount in US Dollar ($): ”;

The “\n” is equivalent to new line, so all texts after “\n” will be displayed on the next line. You can also write the
two statements in one line using “\n”, that is,

cout<<”MONEY CONVERSION \n Enter amount in US Dollar ($): ”;

Both of these statements will result to this program output:

MONEY CONVERSION
\n Enter amount in US Dollar ($):

If you want another line of space in between, you can just add another new line (“ \n”) in your text display. That
is,

cout<<”MONEY CONVERSION \n\n ”;


cout<<”Enter amount in US Dollar ($): ”;
Or
cout<<”MONEY CONVERSION \n\n Enter amount in US Dollar ($): ”;

These formats will produce this program output:

MONEY CONVERSION
\n
\n Enter amount in US Dollar ($):

For Line 7, you are displaying the value of a variable instead of texts. You can use the same cout statement, but
without the quotation marks. Hence, the equivalent program code for Line 7 is
cout<<pesoAmount;

You can also write both texts and variables in one line. For instance, Lines 6 & 7 may be written as

cout<<“Equivalent amount in Philippine Peso (PhP): ”<<pesoAmount;

In this format, only a single cout statement is used but it separates the text from the variable with insertion
operator “<<”. Assuming that the computed value for pesoAmount is 41, this line will have the program output
below:

Equivalent amount in Philippine Peso (Php) : 41

If you want to add some texts after the pesoAmount, you can write it as

cout<<“Equivalent amount Philippine Peso (PhP): ”<<pesoAmount<<” .”;

In this code, we added a period after the variable. This line will have this output:
Equivalent amount in Philippine Peso (Php) : 41 .
61 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

NOTE: To be able to use output streams (as well as input streams), make sure that the iostream library is
included in the include directive. That is,
#include<iostream.h>
VARIABLE DECLARATIONS. A review on the basic layout (see Table 4.2) for C++ program will show you that
before the statements, you have variable declarations. The variables for this program are: dollarAmount and
pesoAmount.

A variable is an identifier that is used to name and store data values.

ALL VARIABLES USED IN THE PROGRAM MUST BE DECLARED. Therefore, the equivalent Line 7 code in the
cout statement will not work unless you have declared it.

Variable Declaration allows users to define what kind or type of data will be stored in the variable. Below
shows the details on how you are going to implement your variable declarations.

Variable Declaration
Syntax type_name var_name_1, var_name_2, …, var_name_last;
type_name: this indicates the data type of the variable. Examples of data types
are int, double, float, and char (see Data Types for other types).

Semantics var_name_1, var_name_2, …, var_name_last: this indicates the list of variable


names declared. The variables are separated by a comma. Variable names are
identifiers, so make sure that variable names are valid, i.e. it follows the criteria
in naming identifiers.

Based on the Money Conversion algorithm, the equivalent program code for variable declaration is:
int dollarAmount, pesoAmount;

Or if declared separately, it can be written as:


int dollarAmount;
int pesoAmount;

The word “int” is type name or data type and dollarAmount and pesoAmount are the variable names.
Make sure that your variables are proper identifiers. The int type means that the value can hold whole number
values from -32,767 to 32,767 (see section on Data Types for more information).

INPUT STREAMS. If C++ has cout statement to output texts or values, it also has cin statement to store values
into a variable.

cin statement: sets the variable equal to the values typed in at the keyboard. It
uses the extraction operator, which is written as >>, (two “greater than” signs). The
standard input device is usually the keyboard.

62 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

The table below will show you how to use cin statements.

Input Streams
Syntax cin>>variable_name;

Semantics variable_name: any declared variable

For the Money Conversion algorithm, Line 4 accepts amount in US dollar and the value is stored in the
variable dollarAmount. Using the cin statement, the equivalent program code is:
cin>>dollarAmount;
This cin statement means that the input of the user will be stored or saved in the variable dollarAmount.
With this, you can use the value entered by the user for computation purposes. Also note that you need to
include the iostream.h library : #include<iostream.h>

ASSIGNMENT STATEMENTS. In the Money Conversion algorithm, a formula is used to convert or compute for
the equivalent amount in Philippine peso based on the US dollar input value. Writing formulas in program code
is very similar to any mathematical formula. In programming terms, these mathematical formulas are called
assignment statements.

Assignment Statements are statements that change the value of a variable


either by computation, operation, or simply assigning a constant value.

In the conversion formula, an asterisk (*) is used to represent multiplication. In C++, we also use the
same symbol for multiplication (see Table 4.1 Arithmetic Operators). The assignment statement table below will
show you how to create a formula in your source code.

Assignment Statements
Syntax variable_name = expression;

Semantics variable_name: any declared variable


expression: this could be a constant or a combination of variables,
operators, or constants (similar to a formula in Algebra).

For this algorithm, the equivalent program code for the formula in Line 5 is:
pesoAmount = dollarAmount * 41;

In this assignment statement, the value of the variable dollarAmount is the value entered by the user.
This value is multiplied by the exchange rate which is 41. The resulting value will then be stored in the variable
pesoAmount.

Note that the formula, in program code, is exactly the same as in the algorithm. However, this is not
always the case in all formulas. The only difference in the program code is the semicolon(;). Don’t forget to
include the semicolon in your statements (as shown in the syntax). Table 4.1 shows the arithmetic operators that

63 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

are used in C++ programming.


Table 4.1 Arithmetic Operators
Operator Function
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (remainder)

You can refer to this table when you want to create equivalent assignment statements for your formula.
These operators are very similar to the operators used in a normal algebraic formula equations except the
modulus operator. The modulus operator (%) computes for the remainder when the two numbers are divided.
For example,
x = 7%6;
In the above assignment statement, 7 will be divided by 6 and the remainder will be the value of x,
hence, x = 1. You will use of these operators once you deal with arithmetic expressions (see section on
Arithmetic Expressions).

MONEY CONVERSION PROGRAM CODE

Line Money Conversion


Money Conversion Program Code
No. Algorithm
1 START #include<iostream.h>
variable declarations
int main ()
{
int dollarAmount, pesoAmount;
output streams
2 Output message “MONEY cout<<”MONEY CONVERSION”;
CONVERSION”
3 Output message “Enter amount cout<<”Enter amount in US Dollar ($): ”;
in US Dollar ($): ” input stream
4 Input dollarAmount cin>>dollarAmount;
5 Compute pesoAmount = pesoAmount = dollarAmount * 41; assignment
dollarAmount * 41 statement
6 Output message “Equivalent cout<<”Equivalent amount in Philippine Peso (PhP): ”;
amount in Philippine Peso (PhP):

7 Output pesoAmount cout<<pesoAmount; output streams
8 END return 0;
}

The table above shows the Money Conversion algorithm and its equivalent program code. The lines on
the algorithm are translated to input streams, output streams, variable declarations, and assignment statements.

Try to make some modifications to this code and see how it affects your program. Also, try to apply the
other formats discussed here to see the differences in the outputs. Now, are you ready to create a program
similar to our Money Conversion Problem? Do the next activities to exercise your programming skills! Enjoy!

64 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Things To Do!

Programming Exercises 3

Write a program (with algorithm) that will compute for the area of a triangle given its base and height
using the formula below. The output can be displayed in whole numbers (using int data type).

Area of a triangle = 0.5 * base * height

Algorithm C++ Program Code

65 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercises 4

You are planning to create a new account in a given bank. That bank offers 10% annual interest rate to its
clients. That is, if you have Php 100 in your account, you will have Php 110 after a year. Write a program (with
algorithm) that will allow you to calculate the total amount with interest rate given the initial value of your
account.

Sample Program Output:

BANK ACCOUNT DETAILS

Initial Value (Php) : 100


Amount after a year (Php) : 110

Algorithm C++ Program Code

66 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercises 5

In an all-veggie pizza delivery company, it takes 15 minutes to make one pizza and 20 minutes to deliver
to their customers. Write a program (with algorithm) that will determine the total delivery time (in hours and
minutes) given the number of pizza being ordered. NOTE: You can use as many variables as needed to solve this
problem. Hint: You can use the modulus operator to determine the equivalent number of hours.

Sample Program Output 1: Sample Program Output 2:

ALL-VEGGIE PIZZA DELIVERY ALL-VEGGIE PIZZA DELIVERY

No. of pizza ordered : 1 No. of pizza ordered : 3


Total Delivery Time Total Delivery Time
Hours - 0 Hours - 1
Algorithm C++ Program Code

Variable Initializations and Constants

67 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Have you ever heard of constants? In mathematics, you learned that variables, like x and y and
sometimes z, can have different values depending on what values you assign to it. However, there are some
values that are constant. These are values that rarely change and sometimes never change.

There are a lot of constants around. The number of days in a week never changes. The number of days in
a year changes every after 4 years. In mathematics, the most popular constant is pi (π). Here, you will be able to
enhance your previous programs by implementing variable initializations and constants.

Try This!

In the previous programming exercises, you were able to use different variables
to assign values from the user (inputs) as well as for computation (assignment
statements). Consider the formula below based from the money conversion
problem,
pesoAmount = dollarAmount * 41

identify the possible variables and constants.

Think Ahead!

Based from the given problem, which value in the formula always changes?
____________________________________________________________________________________________
____________________________________________________________________________________________
__________________________________________________________________________________

Which value remains constant regardless of the given dollar amount value?
____________________________________________________________________________________________
____________________________________________________________________________________________
__________________________________________________________________________________

Think of other constants that you use in formulas from the field of mathematics, physics, economics… or just
something you see on the market or in the internet. What are these constants?
____________________________________________________________________________________________
____________________________________________________________________________________________
__________________________________________________________________________________

Think About This!

68 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

In the Money Conversion problem, we assign dollarAmount as the US dollar amount input from the user
and pesoAmount as the converted value in peso. However, the number 41 is a constant value that we assign for
the exchange rate. In programming, we can set this value as part of the initialization or declared as a constant
value.

VARIABLE INITIALIZATION. Variable initializations are used if you want that to already set an initial value to a
variable upon declaration.

The table below shows the format in implementing variable initializations.

Variable Initialization
Syntax type_name variable_name = constant_value;
type_name: this indicates the data type of the variable.
variable_name: this indicates the name of the variable.
Semantics
constant_value: any fixed value, that is, if the data type is an integer, the value
could be any number or if the data type is a character it could be any letters.
(see Data Types for more on the size, value, and range of the data types).

For this problem, you can declare a variable for the exchange rate (i.e. exchangeRate) and assign 41 as its
value. The equivalent program code for this is:

int exchangeRate;
exchangeRate = 41;

Using variable initialization, you can write this code in one line like this, int exchangeRate = 41;

This format already initializes the value of the exchangeRate to 41 upon declaration of the variable. In
your formula or assignment statement, instead of using the actual value (i.e. 41), you can already use the new
variable, that is,

pesoAmount = dollarAmount * exchangeRate;

If you have two (2) exchange rates: dollar to peso and euro to peso rates. Assign a variable for each
exchange rate. Let variables dollarToPeso and euroToPeso represent dollar to peso and euro to peso rates,
respectively. Assuming that 1 USD = Php41 and 1 Euro = Php54. The initializations for these variables can be
written as:

int dollarToPeso = 41;


int euroToPeso = 54;
Or
int dollarToPeso = 41, euroToPeso = 54;

For the code above, we write the initialization in one line separated by a comma (,). This format is very
similar to multiple variable declarations (see Variable Declarations). However, you can only do this if they have

69 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

the same data type (see Data Types).

MONEY CONVERSION PROGRAM CODE (version 2)

Let’s modify our Money Conversion program using variable initializations.

Line Money Conversion


Money Conversion Program Code
No. Algorithm
1 START #include<iostream.h>

int main ()
{
int dollarAmount, pesoAmount;
int exchangeRate = 41;
variable initialization
2 Output message “MONEY cout<<”MONEY CONVERSION”;
CONVERSION”
3 Output message “Enter amount cout<<”Enter amount in US Dollar ($): ”;
in US Dollar ($): ”
4 Input dollarAmount cin>>dollarAmount;
5 Compute pesoAmount = pesoAmount = dollarAmount * exchangeRate;
dollarAmount * 41
6 Output message “Equivalent cout<<”Equivalent amount in Philippine Peso (PhP): ”;
amount in Philippine Peso (PhP):
” assignment statement
7 Output pesoAmount cout<<pesoAmount; using the new variable
8 END return 0;
}

As you can see, the rest of the program is still the same. The difference is that a new variable is created,
an initialization is created, and the new variable is used in the formula. Variable initializations are very useful
when you want to set an initial value to the variable. Take note, initial. It means that the value can still change
inside your program. Therefore, if you don’t want the values to change, then, you can declare it as a constant.

CONSTANTS. Constants are identifiers which do not change its value throughout the program execution.
Constants, like variables, can also have different data types. The table below shows the format on how to declare
constants.

Declaration of Constants
Syntax const type_name const_variable_name_list;
type_name: this indicates the data type of the variable.
Semantics
const_variable_name_list: this indicates the list of variables declared.

As you can see, the declaration of constants is very similar to variable declaration except with the
inclusion of the keyword const.

In the conversion program, you can also declare exchangeRate variable as constant. The equivalent
program code would be,

70 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

const int exchangeRate;


exchangeRate = 41;

And just like in variable initialization, you can also assign a value to your constants upon declaration of
variable, that is,

const int exchangeRate = 41;

Once you declared it this way, the value of the variable exchangeRate will not be changed even if you
store a new value inside your program. Below are snippets of codes (i.e. part of a program) that show the
difference of using a simple variable initialization and using constants.

Line
Snippet A: Using Variable Initialization Snippet B: Using Constants
No
1 int dollarAmount, pesoAmount; int dollarAmount, pesoAmount;
2 int exchangeRate = 41; const int exchangeRate = 41;
3
4 exchangeRate = 51; exchangeRate = 51;
5 pesoAmount = dollarAmount * exchangeRate; pesoAmount = dollarAmount * exchangeRate;

Assuming, the dollarAmount is 100, what do you think will be the value of pesoAmount when you use
snippet A? How about snippet B? As you know, C++ is a structured programming language, that is, it will check
the codes line-by-line.

In the first snippet (A), the initial value for exchangeRate is 41 (Line 2). However in Line 4, using an
assignment statement, the value of the exchangeRate is set to 51. The value that will be used in the formula will
be the latest value, which is 51. Hence, the value of the pesoAmount is 510.

In the second snippet (B), we declared the variable as constant. If you use or try to change the value of a
constant, the compiler will display an error that will tell you that you have used a constant variable in your
assignment statement. Hence, you will not be able to run this particular code.

71 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Things To Do!

Programming Exercises 6

Money Conversion (version 3): Review the program code for Money Conversion problem. Modify the
program (and algorithm) so that it will convert Dollar to Euro. Assuming that the following are the given
exchange rates:
1 Euro = Php 55
1 US Dollar = Php 41

The exchange rates must be declared as constants and with the initial value above. Other variables must
be declared and initialized to zero. See sample output for this problem below:

Sample Program Output:

MONEY CONVERSION

Enter amount in US Dollar: 100


Equivalent amount in Euro : 75

Algorithm C++ Program Code

72 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Data Types

So far in our examples, we have only used the data type int. In reality, not all data values are in whole
numbers. Some data values are not even numbers. It could be in a form of a character or texts. Before choosing a
data type, it is important to identify its use in the program. If the program requires a number, determine if it is an
integer or a real number (i.e. decimal values) the following are the basic data types used in C++:

Try This!

Consider the algorithm below. This algorithm computes for the area of a circle.

1 START
2 Input the size of the circle (small or big)
3 Input the radius of a circle
4 Compute area of a circle = 3.14 * radius * radius
5 Output area of a circle
6 END

Think Ahead!

Given the above algorithm, what variables (either input or output) produce or accept a whole number value?

________________________________________________________________________________________

What variables (either input or output) produce or accept a real number or decimal value?

________________________________________________________________________________________

As you can see, a simple algorithm can already have multiple types of data. Incorrect type of data might
produce an incorrect data or less precise data. For instance, an area of 1 is not equal to 1.75.

73 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think About This!

So far in our examples, we have only used the data type int. In reality, not all data values are in whole
numbers. Some data values are not even numbers, like your name, gender, or course. These are data in a form of
characters or texts.

Before choosing a data type, it is important to identify its use in the program. If the program requires a
number, determine if it is an integer or a real number (i.e. decimal values) the following are the basic data types
used in C++:

o int (integer) is a whole number consisting of an optional sign ( + or -) followed by a sequence of dig -
its. A whole number means that it does not have any decimal values.
o long (long) is also a whole number consisting of an optional sign ( + or -) followed by a sequence of
digits. The difference with int type is that it can hold larger values and also takes up more memory
space.
o float (floating point) is a number which can be written as finite decimal, such as 5.0, -0.789. A float
number consists of an optional sign (+), followed by one or more digits, a decimal point and one or
more further digits. In addition, it includes an optional exponent.
o double (double precision) is a special float which can store more significant digits and have a larger
exponent. It can also take up more space memory.
o char (character) is a single letter , digit, punctuation mark or control symbol recognized by the com-
puter.
o void – value less or null. This is used to declare data types from functions (see section on Functions).

Table 5.1 below shows the different data types that you can use to declare your variables.

Table 5.1 Size and Range of Basic Data Types


Type Name Memory Used Size Range
Integer Type
int 2 bytes +32,767
long 4 bytes +2,147,483,647
Floating Point
float 4 bytes 10-38 to 1038
double 8 bytes 10-308 to 10308
long double 10 bytes 10-4932 to 104932

In the Money Conversion problem, if we consider a more precise value for the exchange rates, then
these values will already be in a decimal format. In this case, we can already use either float or double data
types. Assuming dollar to peso rate is 41.35, the result for pesoAmount would also result in a decimal value. The
equivalent programming code for the variable declarations and initializations is written as

double dollarToPeso = 41.35;


double pesoAmount;
int dollarAmount;

74 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Since the pesoAmount and dollarToPeso have same data type, you can also declare it in one line. The
variable declaration and initialization can be combined to produce this program code,

double pesoAmount, dollarToPeso = 41.35;


int dollarAmount;

In this code, pesoAmount and dollarToPeso both have double data types but the difference is that
dollarToPeso has already an initial value of 41.35. If pesoAmount is declared as int, the decimal point values of
the data will not be considered or will be chopped off.

Line
Sample Data Types Implementation Simulation
No
int data type holds and
1 double dollarToPeso = 41.35; produces integer values
2 int dollarAmount, pesoAmount;
3
4 cin>>dollarAmount; dollarAmount = 10
5 pesoAmount = dollarAmount * exchangeRate; pesoAmount = 10 * 41.35
6 cout<pesoAmount; output pesoAmount = 413

In this example, even if the computed pesoAmount is 413.5, since it is declared as int, then, the program
will only output the integer part of the data. Hence, it is important especially in this problem that an accurate
and precise output must be given.

Now, let’s try to implement some of these data types into your next exercises.

75 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Things To Do!

Programming Exercises 7

Write a program that will compute for the area of a circle given its radius. You can refer to the previous
algorithm for the formula. Note: Use the appropriate data type for the variables in this problem.

Program Code

76 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercises 8

Money Conversion (version 4): Review the Money Conversion (version 3) from Programming Exercises 6.
Consider the new sets of exchange rates below:

1 Euro = Php 55
1 US Dollar = Php 41

Modify the program so that a more precise data is computed. The program must only accept whole
numbers as inputs.

Program Code

77 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Arithmetic Expressions and more Assignment Statements

From the previous activities and exercises, you were able to create and implement formula through
simple assignment statements. You were able to use the arithmetic operators as part of your assignment
statement. However, not all formula is as simple as multiplication or addition of two numbers. Some formula
computes using more than two operators with more than two variables. These long formulas are called
arithmetic expressions. Here, we try to take a look at different arithmetic expressions and how to implement
them in your program codes.

Try This!

Consider the arithmetic expression below:

x = ab + c
d -e

Think Ahead!

Assuming that the values for the variables are the following:

a = 5, b = 4, c = 10, d = 7, e=2

Show your solution. Determine the steps on how to get the value of x.

1 ______________________________________________________________

2 ______________________________________________________________

3 ______________________________________________________________

4 ______________________________________________________________

5 ______________________________________________________________

78 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Did you separate the computation for the expressions in the numerator from the denominator? Did you
apply the MDAS rule? That’s great thinking! Compare your answers to that of your classmates and see how you
differ in your answers.

Think About This!

In most arithmetic expressions, we do not only use a single operator but a combination of multiple
operators. Since we have the modulus operator, we cannot simply use the MDAS (Multiplication, Division,
Addition, and Subtraction) rule. In C++, we follow a certain rule on how to prioritize the computations in a given
expression. We call this the precedence rule.

PRECEDENCE RULE: ( ) , * , / , % , + , -

In a formula, the expression inside the parenthesis is computed first. Then, the priority of the rest of
operations will be based on the precedence rule, that is, multiplication, division, modulus, addition, and
subtraction as the last priority. For example,

x = 8 + (9-3) * 4 / 2

Using the precedence rule, the computation for the above assignment statement will be in the following
order:

 Parenthesis : x=8+6*4/2
 Multiplication : x = 8 + 24 / 2
 Division : x = 8 + 12
 Addition : x = 20

Hence, the value of x for this arithmetic expression is 20.

For our given sample formula in the activity, the numerator and denominator are computed first and
computed separately. In this case, you can use parenthesis to indicated that it should be prioritized in the
computation, that is,

x = (a * b + c ) / (d – e)

For the expression (a * b + c), a and b will be multiplied first and the product will be added to c.
Whatever the computed value is, it will be divided by the expression (d – e).

It is important that you know how to convert this arithmetic expression into C++ expression. The table
below contains sample mathematical formulas translated to a C++ expression.

79 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Mathematics Formula C++ Expression


b2 – 4ac b*b-4*a*c
x(y+z) x*( y+z)
1
1/(x*x+x+3)
x2 + x + 3
a+b
(a+b)/(c–d)
c -d

MORE ASSIGNMENT STATEMENTS. Since we deal with expressions and assignment statements, it is also
important to note that the C++ language has special shorthand coding that simplifies assignment statements.
The table below shows the format on how to write shorthand assignment statements.

Shorthand Assignment Statements


variable_name operator = expression;

Syntax The above syntax is equivalent to

variable_name = variable_name operator expression;


variable_name: any declared variable
Semantics
expression: a formula that can consist of any combination of variables,
operators, and constants

In writing your program, you might encounter computations that require the use and reuse of variables.
Assuming you want to count the number of times a user runs the code and you want to assign this to variable
count. You could create an assignment statement like this,
count = count + 1;
Using the shorthand format, you can write is as, count += 1;

The following are some other examples on the use of shorthand operations:
total = total - discount; total -= discount;
age = age % 50; age %= 50;
total = total + (amount - discount) total += (amount - discount)

Depending on the problem at hand, you might need to change the value of a certain variable which is
dependent on its current value. You can practice and try to apply the shorthand statements in your previous
activities and exercises. When dealing with control statements, this type of statements will really come in hand
(see Flow of Control and Loops).

For now, you must already know the basics of writing a simple C++ program. If you are not yet
comfortable, practice with more problems. Now, do the next exercises to apply the different arithmetic
expressions.

80 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Things To Do!

Programming Exercises 9

The area of a trapezoid is computed using the formula A = ½ h (b1 + b2) where h is the height, b1 and b2
are the bases. Write a program (with algorithm) that will compute for the area of a trapezoid.

Algorithm C++ Program Code

81 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercises 10

A Fahrenheit temperature F can be converted to an equivalent Celsius temperature C according to the


following formula:
C = 5 (F – 32)
9

Write a program that reads in a Fahrenheit temperature as a decimal number and outputs the equivalent
Celsius temperature.

Algorithm C++ Program Code

82 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercises 11

In a retail store, they offer an anniversary sale for their specially designed T-shirts (A, B, and C). For every
Php 1000 total purchases, you will get a 5% discount on Shirt A. Assume that the prices for Shirts A, B, and C are
Php50, Php75, and Php100, respectively.

Write a program (with algorithm) that will accept the number of T-shirts purchased (or quantity) for each
kind and will display the total purchases, discounted amount, and the amount to be payed (i.e. total purchase –
discount).

Sample Program Output 1 (with 5% discount): Sample Program Output 2 (with 2 x 5% discount):

STORE ANNIVERSARY SALE STORE ANNIVERSARY SALE

Enter quantity for Shirt A: 3 Enter quantity for Shirt A: 10

Enter quantity for Shirt B: 2 Enter quantity for Shirt B: 8

Enter quantity for Shirt C: 7 Enter quantity for Shirt C: 10

Total Purchases: Php 1000 Total Purchases: Php 2100


Algorithm
Discounted Amount: Php 7.50 Discounted Amount:Code
C++ Program Php 50.00

Total Amount: Php 992.50 Total Amount: Php 2050.50

83 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

VI. CONTROL STRUCTURES (SELECTION)

Selections Structures
“Would you tell me, please, which way I ought to go from here?”
“That depends a good deal on where you want to get to”, said the Cat.
“I don't much care where--” said Alice.
“Then it doesn't matter which way you go,” said the Cat. (Carroll, 1865)
After having completed the previous section, you are now able to develop simple C++ programs. The capabilities
of your programs, however, are limited. They can evaluate arithmetic or Boolean expressions and show the
appropriate result. However, what happens when you want to do a program that requires the user to select
between choices? For instance, if you need to know if they want to continue or not?

You need knowledge on control structures. These control structures allow conditional processing of statements.
For these structures, the program checks the choice or input of the user and executes statements that should be
done when a certain choice is made. For instance, the program asks the user whether they want to continue or
not… If the user selects “yes” then another set of constructions are executed. However, if the user selects “no”,
logically, the program should end.
These are the kinds of control statements available:

1. The single-selection statement (If )


2. The double-selection statement (if -else)
3. The multiple-selection statement (switch)

Learning Outcomes/Objectives:

At the end of this section, you should be able to:

1. Make use of control structures selection in programming.


2. Compare the functions of the different conditions statements.
3. Perform the hands on activities
4. Create programs using control Structures Selection.
5. To use the multiple selection using switch selection statements

Topic Outline:

1. Introduction to Control Structures Selection


2. Applying Control Structures Selection
3. The multiple selection statement

84 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Try This!
Assuming you want to identify the status of an individual whether he/she
is a minor or an adult, based on the person's age. The tasks include
reading the age of the individual.

Think Ahead!

What is the input needed to solve this problem?


______________________________________________________________________________
______________________________________________________________________________

What is the expected output for this problem?


______________________________________________________________________________
______________________________________________________________________________

At what age will you consider the individual an adult?


______________________________________________________________________________
______________________________________________________________________________

At what age will you consider the individual a minor?


______________________________________________________________________________
______________________________________________________________________________

Given the values, determine the steps to determine the output of this problem.
No. STEPS
1.
2.
3.
4.
5.

Now you have just written your algorithm! Great!

The data or variables that are needed and asked in the problem are the following:

85 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Input : Reading the age of the individual.


Condition : 18 below is a minor, else 18 and above is an adult.
Output : Minor or Adult.

Algorithm :
1. Input the age of the individual

2. if (age <= 18 )

3. display the message “Minor”

4. else

5. display the message “Adult”

If your steps are similar to this, you are very close to creating a good algorithm! Good Job!

Think About This!

In the solutions of many problems, different actions must be taken depending upon the value of the data.
Examples of simple situations include calculating the area only if the measurements are positive, performing a
division only if the divisor is not zero. (Bronson, 1999)

If statement
The figure below shows the flow of instruction using an if-statement.

Figure 6.1 Flowchart of if


statement

86 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Declaration of if statement
If (test expression) {
Syntax statement;
}
if: this is a reserved word.

Semantics test expression: this indicates the condition is declared.

statement: this statement is executed if the test expression is true.

Example:

If (age >= 17 ) {
cout<<”Minor”;
}

if test expression is true, then, statements for the body if, i.e, statements inside parentheses are executed. But, if
the test expression is false, the execution of the statements of the body of if statements are skipped.

For above example, if age = 17 or less, then it will output “Minor”. Otherwise, there will be no output.

The if selection statement is a single-selection statement because it selects or ignores a single action (or, as we
will soon see, a single group of actions). (Gibmonks, 2002)

Relational expressions are sometimes called conditions which checks the values using an relational operator.
Table 6.1 lists the different kinds of relational operators. This is very similar to mathematical conditions.

Examples:
age> 30 size< = 50 temp> 36.5
4<5 flag == done id_number == 123
day != 4 2.0 > 3.3 hours> 40

The following are invalid:


size=<50 // operator out of order (i.e. equals sign first before less than sign)
2.0 >> 3.3 // invalid operator
flag = = done // spaces are not allowed

Relational operator Meaning Example


< Less than Age < 40
> Greater than Age > 18
<= Less than or equal to Age <= 40
>= Greater than or equal to Age >= 18
== Equal to Age == 60
!= Not equal to Age != 100

87 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Table 6.1 Relational operator

 Let's say you are asked to write a pseudocode/algorithm and its equivalent C++ program that prints a
number entered by the user only if the entered number is negative.

Algorithm Source code


#inlcude<iostream.h>
int main()
{
int number;
Display "Enter a number to check:" cout<<”Enter a number to check:”;
Input number cin>>number;
If (number < 0) if (number<0) {
Display the value entered, cout<<”\nNumber is = “<<number;
}
Display “The if statement in C++ program- cout<<”\nThe if statement in C++ programming is easy!”;
ming is easy! return 0;

Output 1:

Enter a number to check: -2


Number = -2
The if statement in C++ programming is easy!

When user enters -2 then, the test expression (number<0) becomes true. Hence, Number=-2 is displayed on the
screen.

Output 2:

Enter a number to check: 5


The if statement in C++ programming is easy!

When the user enters 5 then, the test expression (number<0) becomes false. So, the statement for body of if is
skipped and only the statement not inside the if is executed.

 Let’s try another example, you were asked to write a pseudocode/algorithm and its equivalent C++
program that guesses ATM Card PINs.

Algorithm Source code


#inlcude<iostream.h>
int main()
{
88 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

int number;
Display "Guess my Pin number" cout<<”Guess my Pin number:”;
Input number cin>>number;
If (number ==1234) if (number==1234){
cout<<”You got it!”;
Output “ You got it!” }
return 0;
}

Output 1:

Guess my Pin number: 1234


You got it!

When the user enters 1234, then, the test expression (number==1234) becomes true. Hence, The message “You
got it!” displayed on the screen.

Output 2:

Guess my Pin number: 121

When the user enters 121, then, the test expression (number==121) becomes false. So, the statement for body of
if is skipped.

If...else statement
The figure below shows the flow of instruction using an if...else-statement.

89 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Figure 6.2 Flowchart of if...else statement

Declaration of if...else statement


If (test expression) {
Statement;
}
else (
Syntax
statement;
}

If and else: these are reserved words.

Semantics test expression: this indicates the condition is declared.


statement: the if statement is executed if the test expression is true. Otherwise
if the test expression is false the else statement will be executed.

Example:
if (age >= 17 ) {
cout<<”Minor”;
}
else{
cout<<”Adult”;
}

The if...else statement is used, if the programmer wants to execute some code if the test expression is true and
execute some other code if the test expression is false.

The if...else statement is called a double-selection statement because it selects between two different actions
(or groups of actions). (Gibmonks, 2002)

For the above example, if age = 17 or less, the output is “Minor”. Otherwise, if the Age is 18 or greater than 17,
the output is “Adult”.

 Let’s say you were asked to write a pseudocode/algorithm and its equivalent C++ program to check
whether the number entered by the user is even or odd.

Algorithm Source code


#inlcude<iostream.h>
int main()
{

90 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

intnumber,x;
Display "Enter a number you want to check:" cout<<”Enter a number you want to check:”;
Input number cin>>number;
Let x = number % 2; x= number % 2;
If (x ==0) if (x==0){
Output The value of the number and the word Even cout<<number<<” is Even”;
}
else else{
cout<<number<<” is Odd”;
Output The value of the number and the word Odd }
return 0;
}

Output 1:

Enter a number you want to check: 12


12 is Even

When user enters 12 then, the test expression (x==0) becomes true. Hence, The value of the number and the
word Even is displayed on the screen.

Output 2:

Enter a number you want to check: 11


11 is Odd

When the user enters 11 then, the test expression (x==0) becomes false. The statement for body of else is
executed. Hence, the value of the number and the word Odd is displayed on the screen.
 Let’s try another example, you were asked to construct a pseudocode/algorithm and its equivalent C++
program for determining the area of a circle, provided if the radius of the circle is not a negative number.

Algorithm Source code


#inlcude<iostream.h>
int main()
{
float radius,area;
Display “Please type in the radius” cout<<”Please type in the radius:”;
Input radius cin>>radius;
If ( radius >=0) if (radius>=0.0){
Let area = 3.1416 * radius * radius; area = 3.1416 * radius *radius ;
91 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Output “The area of the circle is =” and the value of the area cout<<”The area of the circle is = “<<area;
}
else else{
cout<<”Sorry a negative radius is invalid”;
Output “Sorry a negative radius is invalid”
}
return 0;
}

Output 1:

Please type in the radius: 3.5


The area of the circle is = 38.48

When user enters 3.5 then, the test expression (radius>=0) becomes true. Hence, The equivalent area of the circle
is displayed on the screen.

Output 2:

Enter a number you want to check: -3.2


Sorry a negative radius is invalid
When the user enters -3.2 then, the test expression (radius>=0) becomes false. The statement for body of else is
executed. Hence, the message “Sorry a negative radius is invalid “is displayed on the screen.

Logical operators
While relational operators can be used to test whether a particular condition is true or false, they can
only test one condition at a time. Often, we need to know whether multiple conditions are true at once. For
example, to check whether we are qualified for an interview at the college of engineering, we have to check
whether our college entrance examination (CET) is at least we got 50 percent and above and our report card
(GPA) is at least 83 percent and above. This would involve 2 comparisons, all of which have to be true.

Logical operators provide us with this capability. Using logical operators, you can combine two or more
conditional expressions.
C++ provides us with three (3) logical operators. The following are the different logical
operators used in C++.

Operator Symbol Form Operation


Logical NOT ! !x true if x is false, or false if x is true
Logical AND && x && y true if both x and y are true, false if otherwise
Logical OR || x || y true if either x or y is true, false if otherwise

92 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Table 6.2 Logical Operators

Logical NOT
Logical NOT operator reverse the output of the condition from false to true or true to false. In other
words, logical NOT flips a Boolean value from true to false or vice versa. For instance, consider the code below:

int x = 5;
int y = 7;

if (!(x == y))
cout<< "x does not equal to y";
else
cout<< "x equals y";

The equivalent logical expression used is

! (x==y)

The expression (x==y) will be evaluated first. For this example, x=5, y=7, the expression will return a false value.
However using logical not (!), the output is reversed to true. Therefore, !(x==y) outputs a true value.

This way, x == y will be evaluated first, and then logical NOT will flip the Boolean result.

Logical NOT (operator !)


Right operand Result
True false
False true
Table 6.3 Logical NOT

Logical OR
The logical OR operator is used to test whether either of two conditions is true. If the left
operand evaluates to true, or the right operand evaluates to true, the logical OR operator returns true. If both
operands are true, then logical OR will return true as well. Otherwise, a false value will be returned.
Example:
#include <iostream.h>

int main()
{
int nValue;
cout<< "Enter a number: ";
cin>>nValue;

if (nValue == 1 || nValue == 2)
93 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

cout<< "You picked 1 or 2";


else
cout<< "You did not pick 1 or 2";
return 0;
}

nValue == 1 true
nValue == 2 false
nValue == 1 || nValue == 2 (true OR false) true
(refer to Table 6.4 for the equivalent result)
In this case, we used the logical OR operator to test whether either the left condition (nValue == 1) or the
right condition (nValue == 2) is true. If either (or both) are true, the logical OR operator evaluates to true, which
means the if statement executes. If neither are true, the logical OR operator evaluates to false, which means the
else statement executes.

Logical OR (operator ||)


Left operand Right operand Result
false false false
false true true
true false true
true true true
Table 6.4 Logical OR

Logical AND
The logical AND operator is used to test whether both conditions are true. If both conditions are
true, logical AND returns true. Otherwise, it returns false.
Example:

94 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

#include <iostream.h>

int main()
{
intnValue;
cout<< "Enter a number: ";
cin>>nValue;

if (nValue> 10 &&nValue< 20)


cout<< "Your value is between 10 and 20";
else
cout<< "You value is not between 10 and 20";
return 0;
}

nValue >10 true


nValue < 20 true
nValue > 10 && nValue < 20 (true AND true) true

In this case, we use the logical AND operator to test whether the left condition (nValue> 10) AND the right
condition (nValue< 20) are both true. If both are true, the logical AND operator evaluates to true, and the if
statement executes. If neither are true, or only one is true, the logical AND operator evaluates to false, and the
else statement executes.

Logical AND (operator &&)


Left operand Right operand Result
false false false
false true false
true false false
true true true
Table 6.5 Logical AND

Nested if...else statement (if...else if....else Statement)


The figure below shows the flow of instruction using a nested if...else-statement.

95 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Figure 6.3 Flowchart of nested if…else statement (if...else if....else Statement)

The if...else statement can be used in nested form when a serious decision is involved.

Declaration of nested if...else statement


If (test expression 1) {
Statement1;
}
else if (test expression 2) (
Syntax
statement2;
}
else {
statement3;
}
If , else if and else: these are reserved words.
test expression: this indicates the condition is declared.
Semantics statement: the statement 1 is executed if the test expression 1 is true. However
if the test expression 1 is false the else if test expression 2 will be evaluated and
if the test expression 2 is true the statement 2 is executed. Otherwise the
statement 3 is executed.

Example:

96 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

if (age >= 17 ){
cout<<”Minor”;
}
else if (age<=59){
cout<<”Adult”;
}
else {
cout<<”Senior Citizen”;
}

How nested if...else works?


If test expression 1 is true, it will execute the code but, if it is false, the control of the program jumps to the else if
part and check test expression 2, then the process continues. If all the conditions are false then, the else
statement is executed.
For the above example, if age = 17 or less, the output is “Minor”. However, if the Age is than 17, and less than or
equal to 59 the output is “Adult”. Otherwise the output is “Senior Citizen.

Let’s have an example of nested if else statement.


 You were asked to write a pseudocode/algorithm and its equivalent C++ program to relate two integers
entered by using == or > or < sign.

Algorithm Source code


#include <iostream.h>
int main(){
int numb1, numb2;
Display “Enter two integers to check” cout<<"Enter two integers to check";
Input numb1,numb2 cin>>numb1;
cin>>numb2;
If ( numb1 ==numb2) if(numb1==numb2){
cout<<"Result: "<<numb1<<” = “<<numb2;
Output “ Result” numb1 = numb2 }
else if (numb1>numb2) else if(numb1>numb2){
cout<<"Result: "<<numb1<<” > ”<<numb2;
Output “Result” numb1 > numb2 }
else else {
cout<<"Result: "<<numb1<<” < “<<numb2;
Output “Result” numb1 < numb2 }
return 0;

Output 1:

Enter two integers to check.


5
3
Result: 5>3
97 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Output 2:

Enter two integers to check.


-4
-4
Result: -4=-4

Output 3:

Enter two integers to check.


5
8
Result: 5<8

In this program, user is asked to enter two integers which are stored in variable numb1 and numb2. Then, the
value of numb1 and numb2 are to be checked, whether it is equal, less than or greater than by using nested if
else statement.

Switch Selection Statement


The figure below shows the flow of instruction using a switch selection statement.

Figure 6.4 Flowchart of Switch Selection Statement

The switch statement allow us to select one from multiple options. It is especially useful when we want
to write a code that makes a selection based on an expression or a variable. switch selection structure consists
of a series of case labels and optional default case as shown below.
98 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

The switch selection statement is called a multiple-selection statement because it selects among many
different actions (or groups of actions).
switch statement works by comparing the value of variable or expression within the parentheses with
values specified in each case. If there is a match, the statements following the case will be executed. If no match
occurs, the default statement is executed. At the end of each case, keyword break must be placed to exit from
the switch immediately after statements execution.

Declaration of switch selection statement


swtich (variable) {
case constant_value1 : statement 1;
break;
case constant_value2 : statement 2;
Syntax
break;
default: last statement;
break;
}
Switch, case, break, and default: these are reserved words.
variable: this indicates the value of the variable.
Semantics
statement: the statement 1 is executed if the case constant_value1 is equal to the
variable value. However if the variable value is equal to the case constant_value 2 the
statement 2 is executed. Otherwise the last statement is executed.

The execution of switch statement begins with the evaluation of expression. If the value of expression
matches with the constant then the statements following that case execute sequentially until it executes break.
The break statement transfers control to the end of the switch statement. If the value of expression does not
match with any constant, the statement under default is executed.
Some important points about switch statement
1. The expression of switch statement must be of type integer or character type.
2. The default case need not to be used at last case. It can be placed at any place.
3. The case values need not to be in specific order.

Let’s try this example 1


 You request the user to enter a number between 1 and 3.

#include <iostream.h>

int main()
{
int Number;

cout<< "Type a number between 1 and 3: ";


cin>> Number;

99 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

switch (Number)
{
case 1:
cout<< "\nYou typed 1.";
break;
case 2:
cout<< "\nYou typed 2.";
break;
case 3:
cout<< "\nYou typed 3.";
break;
}

return 0;
}

The program above would request a number from the user. If the user types 1, it
would execute the first, the second, and the third cases. If she types 2, the program
would execute the second and third cases. If she supplies 3, only the third case would
be considered. If the user types any other number, no case would execute.

Let’s try this example 2


 You request the user to enter a number between 1 and 3.
#include <iostream.h>

int main()
{
int Number;

cout<< "Type a number between 1 and 3: ";


cin>> Number;

switch (Number)
{
case 1:
cout<< "\nYou typed 1.";
break;

case 2:
cout<< "\nYou typed 2.";
break;

case 3:
cout<< "\nYou typed 3.";

100 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

break;
default:
cout<<”\n Sorry number is not in the list!”;
break;

return 0;
}

When establishing the possible outcomes that the switch statement should consider,
at times there will be other possibilities other than those listed and you will be likely to
consider them. This special case is handled by the default keyword. The default case
would be considered if none of the listed cases matches the supplied answer.

Consider this example:


 Write a pseudocode/algorithm and its equivalent C++ program that asks the user an arithmetic
operator ('+','-','*' or '/') and two operands and perform the corresponding calculation on the
operands.
Algorithm Source code
# include <iostream.h>
int main(){
char operator;
float num1,num2;
Display the following operators +, -, * or / cout<<"Enter operator +, - , * or / :\n";
Input operator cin>>operator;
Display Enter two operands cout<<"\nEnter two operands:\n";
Input num1,num2 cin>>num1;
cin>>num2;
switch(operator)
{
if in case operator is = “+” case '+':
add num1 and num2 cout<<"num1+num2= “<<(num1+num2);
Output the sum break;
if in case operator is = “-“ case '-':
subtract num1 and num2 cout<<"num1-num2= "<<(num1-num2);
Output the difference break;
if in case operator is = “*” case '*':
multiply num1 and num2 cout<<"num1*num2= "<<(num1*num2);
Output the product break;
if in case operator is = “/” case '/':
divide num1 and num2 cout<<"num2/num1= "<<(num1/num2);
Output the Quotient break;
101 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

If in case the operator is not correct default:


Output “Error! Operator is not correct” cout<<”Error! Operator is not correct";
break;
}
return 0;

Output 1:

Enter operator +, -, * or / :
/
Enter two operators:
34
3
num1/num2=11.33

Output 2:

Enter operator +, -, * or / :
+
Enter two operators:
34
3
num1+num2=37.0

Output 3:

Enter operator +, -, * or / :
-
Enter two operators:
34
3
num1/num2=31

Output 4:

Enter operator +, -, * or / :
*
Enter two operators:
34
3
num1/num2=102

This program takes an operator and two operands from the user. The operator is stored in variable operator and
two operands are stored in num1 and num2. Then, switch...case statement is used for checking the operator
entered by user. If user enters + then, statements for case '+' is executed and program is terminated. If user enters
- then, statements for case '-' is executed and program is terminated. This program works similarly for * and /
102 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

operators. But, if the operator does not match any of the four characters [ +, -, * and / ], default statement is
executed which displays an error message.

Things To Do!
Programming Exercise 11:
Write a pseudocode/algorithm and its equivalent C++ program that will ask the user to enter
three numbers, and will find the largest number among the three numbers entered by user.

103 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercise 12:


Write a pseudocode/algorithm and its equivalent C++ program that will ask the user to enter a
character and check whether that character is a vowel or consonant. (used nested if else if
statement).

104 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercise 13:


Each disk drive in a shipment of these devices is tamped with the code from 1 through 4, which
indicate a drive manufacturer, which are as follows:

Code Disk Drive Manufacturer


1 3M Corporation
2 Maxwell Corporation
3 Sony Corporation
4 Verbatim Corporation

 Write a pseudocode/algorithm and its equivalent C++ program that accepts the code number
as an input and based on the value entered displays the correct disk drive manufacturer.
(Bronson, 1999)(used switch selection statement).

105 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercise 14:

A student’s letter grade is calculated according to the following schedule:

Numerical Grade Letter grade


Greater than or equal to 90 A
Less than 90 but greater than or equal to 80 B
Less than 80 but greater than or equal to 70 C
Less than 70 but greater than or equal to 60 D
Less than 60 F

 Using this information, write a pseudocode/algorithm and its equivalent C++ program that
accepts a student’s numerical grade, converts the numerical grade to an equivalent letter
grade, and displays the according grade. (Bronson, 1999)(used if else if statement).

Sample Output:
Pls. enter a student’s numerical grade: 80
The equivalent letter grade is = B

106 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

VII. Repetitive Control Statements

Learning Outcomes/Objectives:

At the end of this section, you should be able to:


1. Use the syntax of the different repetitive statements in a program
2. Compare the different repetitive statements from one another
3. Select the best repetitive statement to be used in a certain problem
4. Create program codes using the different repetitive statements

Topic Outline:

1. Introduction to Repetitive Control Structures


a. while statements
b. do… while statement
c. for statement
2. Application of Repetitive Control Statements

Repetitive Control Structures

Have you observed the work of a cashier in a grocery store? Or a waiter in a restaurant? Did you
know that they are doing a repetitive process? For each customer, they ask the same questions,
get same sets of information, and follow the same computations. This procedure is repeated for
every customer until there are no more customers or their duty for work is over.
A program code is considered to be a good code if it has a good algorithm and codes are
compact. You know by now that the compiler processes your codes line by line. So, the more
lines of codes you have the more time it requires for the compiler to process it. A program with
too much code lines cannot be considered a good program code especially if codes are being
repeated for several times. How can you eliminate repeated codes?
Repetitive Control statement is the structure you need to know to eliminate redundant codes.
Repetitive Control statement repeats execution of codes for several times depending on the
given condition.
These are the kinds of control statements available:
4. The while statement
5. The do…while statement
6. The for statement

107 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Try This!

Do you know anyone who is already working for a company or managing their own
business? It could be your parents, sister, brother, friends, or anybody you know. Ask them
of the nature of their job. And just like the job of a cashier or waiter, ask them which part of
their work is repeated (either repeated daily, weekly, monthly, yearly, or at a certain given
moment or period depending on their job).

Think Ahead!

What is the nature of their work?


____________________________________________________________________________________________
____________________________________________________________________________________________
____________________________________________________________________________________________
________________________________________________________________

Which part(s) of their job are repeated?


____________________________________________________________________________________________
____________________________________________________________________________________________
_______________________________________________________________________

List the factors that contribute to the repetition of their actions? When will they stop doing their job?
____________________________________________________________________________________________
____________________________________________________________________________________________
____________________________________________________________________________________________
________________________________________________________________
The job of a cashier in the counter is repeated for each customer; however, not every job is repeated in
the same manner. Some jobs require them to create reports maybe daily, weekly, monthly, and sometimes yearly
depending on the nature of the job. In some cases, it’s not the entire work that is repeated but only a part of the
work.
The factors that you have identified are the conditions in which certain tasks are repeated or not to be
repeated. This is a very important aspect that you have to identify when dealing with repetitive actions. Imagine
the job of a cashier in the counter, without a certain condition (i.e. a snack break or end of duty), they would be
repeating the tasks forever. This also applies in programming; you do not want your program stuck in an endless
loop.

108 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Think About This!

Repetitive control statements are also called a Repetitive control structure. Sometimes we require a set
of statements to be executed a number of times by changing the value of one or more variables each
time to obtain a different result. This type of program execution is called looping.
WHILE LOOP STATEMENT

The first repetitive statement is the while loop statement. Below is the flow diagram of while loop.

False
Test
Expression

True

loop
Executable
Diagramstatement(s)
7.1 flowchart of while statement

Continue with the


next statement

The flow diagram indicates that a condition is first evaluated. If the condition is true, the loop
body is executed and the condition is re-evaluated. Hence, the loop body is executed repeatedly
as long as the condition remains true. As soon as the condition becomes false, it comes out of
the loop and goes to the statement next to the ‘while’ loop.

Table 7.1. syntax of while statement


Line
Syntax
No.
1 while (condition)
2 { indicates the start of loop
3 Statement_1;
4 Statement_2;
5 statement_3; Statements to be executed
6 . If condition is true
7 .
8 last statement;
9 } indicates the end of loop

109 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

SAMPLE PROGRAM

Find the sum of first ten natural numbers. Natural numbers are positive integers (whole numbers).

How it Works Program

1. Initialize the loop control variable 1 # include <iostream.h>


2. Test the loop control variable 2 int main ( )
3. Update the loop control variable 3 {
4 int n, total = 0 ;

5 n=1;
6
7 while (n < = 10)
8 {
9 total + = n ;
10 n++;
11 }
12
13 cout << “sum of first ten natural number”:
14 cout << total :
15
16 return 0;
17 }

Sample Problem with running program code (while loop)

A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are
available to you. Determine the class average on the quiz.

110 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Algorithm C++ Program


#include <iostream.h>

int main()
{
int total;
1 initialize total=0 and
int gradeCounter;
gradeCounter=1
2 compare gradeCounter if less than int grade;
or equal to 10 int average;
3 if true
a. get grade as input total = 0;
b. add inputted grade to gradeCounter = 1;
total
c. increment gradeCounter while ( gradeCounter <= 10 )
by 1 {
(repeat step 3 while condition is cout << "Enter grade: ";
true) cin >> grade;
4 compute of average total = total + grade;
5 display output (class average)
gradeCounter = gradeCounter + 1;
}

average = total / 10;


cout << "Class average is " << average <<
endl;
return 0;
}

Sample Possible Output:

Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79

111 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Program Simulation

initialize
total=0
gradeCounter=1
condition input total increment
(gradeCounter<=10) (grade) gradeCounter
gradeCounter=1 true 98 98 2
gradeCounter=2 true 76 174 3
gradeCounter=3 true 71 245 4
gradeCounter=4 true 87 332 5
gradeCounter=5 true 83 415 6
gradeCounter=6 true 90 505 7
gradeCounter=7 true 57 562 8
gradeCounter=8 true 79 641 9
gradeCounter=9 true 82 723 10
gradeCounter=10 true 94 817 11
gradeCounter=11 false 817
Average=81

DO-WHILE LOOP STATEMENT

Another repetitive statement is the do – while loop statement. Just like the while loop, the do-while
loop also repeats execution of statements. Below is the diagram of the do – while loop.

Executable statement(s)

True
(loop)
Test
expression
Diagram 7.2 flowchart of do…while statement
False

Continue with the


next statement

The flow diagram indicates that after each execution of the loop body, if the condition is
true, the loop body is executed again. If the condition evaluates to false, loop exit occurs
and the next program statement is executed. Note that the loop body is always executed at
least once.

Table 7.1. syntax of do…while statement


Line
Syntax
No.
1 do

112 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

2 { indicates the start of loop


3 Statement_1;
4 Statement_2;
5 statement_3; Statements to be executed
6 . if condition is true
7 .
8 last statement;
9 }while (condition); Will terminate loop if condition is false

SAMPLE PROGRAM
Find the sum of the first N natural number.

How it Works Program

1. Initialize the loop control variable 1 # include <iostream.h>


2. Update the loop control variable 2 int main ( )
3. Test the loop control variable 3 {
4 int N, number = 0, sum = 0;
5
6 cin >> N ;
7
8 do
9 {
10 sum + = number;
11 number + + ;
12 } while (number < = N) ;
13
14 cout << sum;
15
16 return 0;
17 }

Sample Problem with running program code (from while loop to do-while loop)

A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are
available to you. Determine the class average on the quiz.

Algorithm C++ Program


113 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

#include <iostream.h>

int main()
{
int total;
1 initialize total=0 and
int gradeCounter;
gradeCounter=1
2 get grade as input int grade;
3 add inputted grade to total int average;
4 increment gradeCounter by 1
5 repeat step 2,3 and 4 while total = 0;
condition is true gradeCounter = 1;
6 compute for average
7 display output (class average) do
{
cout << "Enter grade: ";
cin >> grade;
total = total + grade;
gradeCounter = gradeCounter + 1;
} while ( gradeCounter <= 10 );

average = total / 10;


cout << "Class average is " << average <<
endl;
return 0;
}

Sample Possible Output:

Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79

Program Simulation

114 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Initialize
total=0
gradeCounter=1
input total increment condition
(grade) gradeCounter (gradeCounter<=10)
gradeCounter=1 98 98 2 true (loop)
gradeCounter=2 76 174 3 true(loop)
gradeCounter=3 71 245 4 true(loop)
gradeCounter=4 87 332 5 true(loop)
gradeCounter=5 83 415 6 true(loop)
gradeCounter=6 90 505 7 true(loop)
gradeCounter=7 57 562 8 true(loop)
gradeCounter=8 79 641 9 true(loop)
gradeCounter=9 82 723 10 true(loop)
gradeCounter=10 94 817 11 false(exit loop)
Average=81

FOR LOOP STATEMENT

The last repetitive statement is the for loop statement. Just like the first two repetitive state-
ments, its main function is to repeat execution of statement(s) while condition remains true.
With the two repetitive statements, the for statement work more likely than the while loop. But
in addition, for statement provides specific locations to contain an initialization statement and a
statement to be executed after every iteration.

From previous
statement

initialization condition expression

Condition
Condition is false is true

Continue with the


next statement Statement(s)

Diagram 7.3 flow of execution using the for statement

Upon entering the for loop, the initialization statements is first executed. Then it will perform or
test the condition. If the condition is true, the statement(s) will be executed. After execution of
the statement(s), the expression is then executed. Then again test the condition and execute
the statements if the condition is still true. Same procedure is being followed until the condition
will become false.

Table 7.3 syntax of for statement

115 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Lin
e Syntax
No.
1 for(initialization; condition; expression)
2 { indicates the start of loop
3 Statement_1;
4 Statement_2;
5 statement_3; Statements to be executed
6 . if condition is true
7 .
8 last statement;
9 } indicates the end of loop

SAMPLE PROGRAM

Here is an example using a for loop:

How it Works Program

1. Initialization is executed. Generally it is 1 # include <iostream.h>


an initial value setting for a counter 2 int main ( )
variable. This is executed only once. 3 {
2. Condition is checked. If it is true the 4 int y;
loop continues, otherwise the loop 5
ends and statement is skipped (not ex- 6 for(y=5; y >=0; y--)
ecuted). 7 {
3. Statement is executed. As usual, it can 8 cout <<y << ", ";
be either a single statement or a block 9 }
enclosed in braces { }. 10
4. Finally, whatever is specified in the in- 11
crease field is executed and the loop 12 cout << "\nFIRE!\n";
gets back to step 2. 13
14 return 0;
15 }

Sample Possible Output:

116 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

5,4,3,2,1,0,
Fire

Program Simulation

initialize Display value


y=5 of y
condition Decrement y
(y>=5) by 1
y=5 true(loop) 5 4
y=4 true(loop) 4 3
y=3 true(loop) 3 2
y=2 true(loop) 2 1
y=1 true(loop) 1 0
y=0 true(loop) 0 -1
y=-1 false(exit
loop)
Display “Fire”

Things To Do!

117 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercise 16:


Rewrite the codes of the sample program given for while and do while loop. This time,
use the for loop instead.

Programming Exercise 17:


Write a program to compute for the total amount to be paid by the customer in
purchasing items. The program should display a list of five (5) items with their
corresponding prices. The user selects items from the list and inputs the item number to
118 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

be purchased (based on the list) and the quantity for each item to be purchased. This
action will be repeated until the user does not select anymore items. The program will
display the total amount to be paid by the customer.

Programming Exercise 18:


Write a program that determines the factors of an integer value.

119 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercise 19:


Write a program that determines the greatest common factor of two integer values.

120 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

121 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

VIII. Functions

Learning Outcomes/Objectives:

At the end of this section, you should be able to:


1. Use predefined function(s) in a program
2. Create your own function
3. Write programs in modular approach
4. Use different types of parameters in a function

Topic Outline:
1. Introduction to Functions
2. Pre-defined functions
3. Programmer define functions
4. Types of parameters

Functions

After completing the previous sections, you are now equipped with the basics of C++
programming. You know that programs are created to solve problems. So far, you only created small
programs that solve a specific problem. However, most of the programs such as websites or games
composed of smaller programs that are joined and integrated to create one huge application. It sounds
complicated, right? And maybe you can already imagine thousands lines of codes. In most cases, these
huge applications are divided into chunks for easy programming and management not just by a single
programmer but also for a group of programmers. How? Well, easy… functions!
Let’s take a look at your own television sets. Do you know how televisions are manufactured?
Production of television consists of several lines (of production) and each line is assigned for a special
task. At the end of each production line, outputs are being checked before proceeding to the next
production line. This is done to assure that the unit is functional.
In programming, you can also create programs chunk by chunk. Each chunk is a part of a huge
program. Each chunk is being tested of its functionality before embedding to the huge program. These
chunks are called functions. This programming technique is called the modular approach.

Try This!

During enrolment, after filling up the red form, how many steps have you
undergone before getting officially enrolled?

Think Ahead!
122 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Why does enrollment process divided into steps?


____________________________________________________________________________________________
________________________________________________________________________________________
If only one person is in-charge for the entire enrollment process, will the enrollment become faster? Will the
enrollment process have lesser error?
____________________________________________________________________________________________
____________________________________________________________________________________________
________________________________________________________________________________

Think About This!

A function is a subprogram that is executed when it is called from some point of the program, it
will not be executed unless it is called. The statement used to execute a function is called the
function call. A function call is an expression consisting of the function name followed by the ar-
guments enclosed in parenthesis.

One of the advantages of using functions to divide programming task into subtasks is that differ-
ent people can work on different subtasks. Also, it is easier to debug a program with lesser lines
of codes compared to a huge program.

There are two types of functions two namely:

1. Pre-defined function
2. Programmer Defined Function

Predefined Function

C++ comes with libraries of Predefined functions that you can use in your program. These Prede-
fined functions are ready made function and has already been defined. Below are some prede-
fined functions.

Name Description Type of ar- Type of Library Example Value


of func- guments value re- header
tion turned
Sqrt Square root double double math.h sqrt(4.0) 2.0
Pow powers double double math.h pow(2.0,3.0) 8.0
Abs Absolute int int stdlib.h abs(-7) 7
value for int abs(7) 7
Labs Absolute long long stdilib.h labs(-70000) 70000
value for long labs(70000) 70000
Fabs Absolute double double math.h fabs(-7.5) 7.5
value for dou- fabs(7.5) 7.5
ble
Ceil Ceiling (round double double math.h ceil(3.2) 4.0
up) ceil(3.9) 4.0
123 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Floor Floor (round double double math.h floor(3.2) 3.0


down) floor(3.9) 3.0
Hypot Hypothesis of double double math.h hypot(3.0,4.0) 5.0
a triangle
Table 8.1 some example of Predefined function

SAMPLE PROGRAM

The relationship between the sides (a, b) of a right triangle and the hypotenuse (h) is given
by the Pythagorean formula

a2 + b2 = h2
Write a program that reads in the lengths of the two sides of a right triangle and computes the
hypotenuse of the triangle.

Program Code 1
#include <iostream.h> library for cin and cout
#include <math.h> library for predefined functions sqrt and
pow

main ()
{
double a, b, h; variable declarations; type double since
arguments for sqrt and pow are double,
also the data type of the value returned by
the function sqrt is also double

cout<<”\nEnter sides of the triangle…”


cout<<”\nside a: “;
cin>>a;
cout<<”\nside b: “;
cin>>b;

h = sqrt ((pow(a, 2.0)) + (pow(b, 2.0))); function call for pow and sqrt; pow is
executed first then sqrt

cout<<”\nhypotenuse of the triangle is


“<<h<<endl;
return 0;
}

Program Code 2
#include <iostream.h> library for cin and cout
#include <math.h> library for predefined functions hypot

124 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

main ()
{
double a, b, h; variable declarations; type double since
arguments for hypot is double and the
data type of the value returned by the
function hypot is double

cout<<”\nEnter sides of the triangle…”


cout<<”\nside a: “;
cin>>a;
cout<<”\nside b: “;
cin>>b;

h = hypot(a,b); function call for hypot

cout<<”\nhypotenuse of the triangle is


“<<h<<endl;
return 0;
}

Program Output for both program codes:

Enter sides of the triangle…

side a: 3

side b: 4

hypotenuse of the triangle is 5

Programmer Defined Function


C++ allow programmers to create their own functions. This is used to make the program more
organized and structured. These functions are called programmer defined functions.
A programmer-defined function is divided into two parts. The Function Prototype that tells the
compiler what type of data the function will return, how the function will be called, as well as what
arguments the function can be passed. It is declared after the include directives, before the main
function.

Function prototype
Syntax return-type function_name ( arg_type arg1, ..., arg_type argN );

125 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

return-type: data type of the value returned after executing the function.
For functions that has nothing to return after execution, void type
specifier is used
function_name: name of the function and must start with either a letter
or the underscore symbol, and all the rest of the characters must be
letters , digits or the underscore symbol, like the identifiers.

Semantics

arg_type: the data type for each parameter or argument

arg1, argN: identifier which can be assigned a value when the function is
called

Below is an example for defining a function prototype.


int mult ( int x, int y );

 This prototype specifies that the function mult will accept two arguments, both
integers, and that it will return an integer.

The second part of defining a function is the Function Definition. This is declared after the main func-
tion. Function definition begins with the prototype, minus the semi-colon. Then there should always be
a block with the code that the function is to execute. Any of the arguments passed to the function can
be used as if they were declared in the block.

Table 8.2 The general format for defining a function


Line
Syntax
No.
1 return-type function_name (arg_type arg1, ..., arg_type argN) Function heading; similar to function
prototype but without a semicolon
2 { indicates the start of the function
3 variable declaration; local variable(s),only if necessary
4 Statement_1;
5 statement_2; Function body; consists
6 . of executable statements
7 .
8 last statement;
9 return statement; Necessary for functions that returns a value
but optional for void functions
10 } indicates the end of the function

Scope of variables
Variables can be declared global or local to a function. Global variables can be used anywhere in the
program, whether in the main function or within the programmer define functions. Local variables can

126 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

only be used within the function where it is declared.


SAMPLE PROGRAM 1
Program that adds two integers and output the sum. Defines a functions with two parameters,
performs the addition of two integers and returns the sum.

How it Works Program


1. Function prototype. Declaring a func- #include <iostream.h>
tion addition with two parameters both
of type int and the data type return is int addition (int a, int b);
also of type int
2. Function call. Calling the function addi- int main ()
tion passing the value of 5 to a and 3 to {
b. The value returned by the function int z;
addition is assigned to the variable z.
3. Function definition. Returns the sum of z = addition (5,3);
a and b. cout << "The result is " << z;
return 0;
}

int addition (int a, int b)


{
return (a+b);
}
SAMPLE PROGRAM 2
Program that subtracts two integers and output the difference. Defines a functions with two
parameters, performs the subtraction of two integers and returns the difference. The programs shows
four(4) different ways on how to call a function.

How it Works Program


1. Function prototype. Declaring #include <iostream.h>
a function subtraction with
127 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

two parameters both of type int subtraction (int a, int b);


int and the data type return is
also of type int. int main ()
2. Assigning values to x and y {
3. Function call. Calling the func- int x=5, y=3, z;
tion subtraction passing the
value of 7 to a and 2 to b. The z = subtraction (7,2);
value returned by the function
subtraction is assigned to the cout << "The first result is " << z ;
variable z. cout << "The second result is " <<subtraction(7,2)<<endl;
4. Displaying the value of z. cout << "The third result is " << subtraction (x,y)<<endl;
5. Another function call. Calling
z= 4 + subtraction (x,y);
the function subtraction pass-
ing the value of 7 to a and 2 to cout << "The fourth result is " << z << endl;
b. The value returned by the
function subtraction is dis- return 0;
played. }
6. Another function call. Calling
the function subtraction pass- int subtraction (int a, int b)
ing the value of x to a and y to {
b. The value returned by the int r;
function subtraction is dis-
played. r=a-b;
7. Another function call. Calling
the function subtraction pass- return (r);
ing the value of 7 to a and 2 to }
b. The value returned by the
function subtraction is added
to 4 and assigned the sum to z
8. Function definition. Function
with local variable r. Variable r
can only be used within this
function. Return the difference
of two numbers

SAMPLE PROBLEMS WITH PROGRAM CODES


1. A liter is 0.264179 gallons. Write a program that will read in the number of liters of gasoline con-
sumed by the user’s car and the number of miles traveled by the car; and will then output the num -

128 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

ber of miles per gallon the car delivered. Your program should also allow the user to repeat this cal -
culation as often as the user wishes. Define a function to compute the number of miles per gallon.

#include <iostream.h>
#include <conio.h>
#include <ctype.h>

double miles_per_gal (double lit_gal, double miles_trav);

int main()
{
double nlg, nmt, nmg;
char ans;

do
{
cout<<”\nEnter number of liters of gasoline consumed by user’s car: “;
cin>>nlg;
cout<<”Enter number of miles traveled by the car: “;
cin>>nmt;

nmg = miles_per_gal (nlg, nmt);

cout<<”The number of miles per gallon the car delivered is “<<nmg<<endl;


cout<<”Want another calculation [Y/N]? “;
cin>>ans;
} while (toupper (ans) = = ‘Y’);

return 0;
}

double miles_per_gal (double lit_gal, double miles_trav)


{
return (( lit_gal * 0.264179 ) / miles_trav );
}

Sample output

Enter number of liters of gasoline consumed by user’s car:3


Enter number of miles traveled by the car:2
The number of miles per gallon the car delivered is 0.3962685
129 | P a g e
Want another calculation [Y/N]?y
CC 101. Computer Programming 1 SY 2017-2018

2. Write a program that will display the square of integer 1 to 10.

#include <iostream.h>

// function prototype
int compSquare( int y );
void displaySquare( int S );

int main()
{
int x, square;

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


{
square=compSquare( x ); //calling the function compSquare with value of x as
argument
displaySquare(square); //calling the function displaySquare with the value of
square as argument
}

cout << endl;

return 0;
}

// function definition
int square( int y ) // The parameter y will accept the value of x
{
return y * y; //return the square of y
}

void displaySquare( int S ) //The parameter S will accept the value of square
{
cout<<S<<” “; //display the value of S
}

Sample output
130 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

1 4 9 16 25 36 49 64 81 100

Types of Parameters

In defining a programmer defined function, parameters are used to accept the values of the arguments
that are being passed in the function call. There are two types of parameters.
One type of parameter if the call by value parameters. In call-by-value, the argument expression is
evaluated, and the resulting value is bound to the corresponding variable in the function (frequently by
copying the value into a new memory region). If the function or procedure is able to assign values to its
parameters, only its local copy is assigned — that is, anything passed into a function call is unchanged
in the caller's scope when the function returns.
Another type of parameter is the Call by reference parameters. In call-by-reference (also referred to as
pass-by-reference), a function receives an implicit reference to a variable used as argument, rather
than a copy of its value. This typically means that the function can modify (i.e. assign to) the variable
used as argument—something that will be seen by its caller. Call-by-reference can therefore be used to
provide an additional channel of communication between the called function and the calling function.

SAMPLE PROGRAM 1
How it Works Program

1. Function prototype with call by value pa- #include <iostream.h>

131 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

rameter.
2. Function prototype with call by reference void changeVal_x (int a);
parameter. void changeVal_y (int& a);
3. Function prototype to display the values of void displayNewVal(int a, int b);
x and y.
4. Declaration of variables x and y and assign- int main ()
ing value. {
5. Function calls. int x=5, y=5;
6. Function definitions.
changeVal_x ( x );
changeVal_y ( y );

displayNewVal(x, y);

return 0;
}
void changeVal_x (int a)
{
a++;
}
void changeVal_y (int& a)
{
a++;
}
void displayNewVal(int a, int b)
{
cout<< “value of x is “ << x << endl
<< “value of y is “ << y <<endl;
}

Things To Do!
Programming Exercise 20:

A quadratic equation is one of the form ax2 + bx + c =0. Write a program to solve such equations for
x using the quadratic formula:

132 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

x = ( - b + ( b2 – 4ac )2 ) / 2a

Your program will output all real number values that, when substituted for x, will make the left
hand side equal to zero. The input to the program consists of the three coefficients a, b, and c.

Programming Exercise 21:

Enhance your code of problem one. This time, define functions to compute for the values of x
and to display the computed values.

133 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Programming Exercise 22:

In order to discourage excess consumption, an electric company charges its customers a lower
rate, namely $0.11, for each of the first 250 kilowatt hours, and higher rate of $0.17 for each
additional kilowatt hour. In addition, 10% surtax is added to the final bill. Write a program to
calculate electric bills given the number of kilowatt hours consumed as input. Use two function

134 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

declarations: one to compute the amount due without the surtax and one to compute the total
due with surtax.

Programming Exercise 23:


Write a function declaration for a function called grader that takes a numeric score and
returns a letter grade. Grade has one argument of type integer. Use the rule that 90 to
100 is an A, 80 to 89 is a B, 70 to 79 is a C and less than 70 is an F.

135 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

APPENDIX A

TURBO C++ Integrated Development Environment (IDE)

The Turbo C++ is an IDE that implements C++ programming languages. This document describes
the Turbo C++ IDE environment as well as the procedures to manage data, compile, and run program
source codes. This document includes the following procedures:

136 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

4. The Turbo C++ IDE


5. Creating New Source File
6. Saving Source File
7. Compiling Source File
8. Running Source File
9. Closing Source Files
10. Opening Saved Source Files
11. Exiting Turbo C++ IDE

4. The Turbo C++ IDE

The Turbo C++ It has its own text editor where equivalent source codes are written. The source
files in C++ have .CPP extension. Figure A.1 shows the main screen display of the Turbo C++ IDE. This
IDE program environment also includes windows, error messages, and pull-down menus.

Figure A.1 Turbo C++ IDE

137 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

5. Creating New Source File


To create a new source file, click on File menu and select New.

Figure
A.2 New Source File Menu

A new window for the source file will be loaded (see Figure A.3). The default filename is set to
NONAME00.CPP.

Figure A.3 New Source File Window

138 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Figure A.4 below shows a sample source code written in the text editor window.

Figure A.5 Sample Source File

6. Saving Source Files

To save the written source code, press F2 or click on File menu and select Save.

Figure A.6
Saving Source File

139 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

A window dialog will appear for the user to change the filename of the source file (see Figure A.7). The
source files are using .CPP extension. Figure A.7 below shows a file with a filename changed to HELLO.CPP. Click
on the OK button after the filename is changed.

Figure A.7 Setting of Filenames

After file is saved, the name of the source code window will appear (see Figure A.8).

Figure A.8 Sample Saved File

140 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

7. Compiling Source File

To compile source codes, press ALT-F9 or click on Compile menu and select Compile.

Figure A.9 Compiling Source Codes

A compiling dialog message will appear once the source code is being compiled. Figure A.10
shows a sample message for successfully compiled source code while Figure A.11 shows a sample
message for compiled source code with error.

Figure A.10 Sample Compiling Message

141 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Figure A.11 Sample Compiling Message with Error

For source codes with errors or warnings, the C++ compiler also displays the equivalent list of
errors found and which line of codes the error exists (see Figure A.12).

Figure A.12 Error List

The all errors will be included under Message window. Running through the errors will point out
the equivalent code where the error can be found.

142 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

8. Running Source File

To run a source code, press CTRL-F9 or click on the Run menu and select Run (see Figure A.13).

Figure A.13 Running Source Codes

An equivalent linking message will appear to show the status of the run similar. The status of the
error will be similar to Figure A.11. In case, there are no errors an equivalent output message (DOS
mode) will be shown (see Figure A.14).

Figure A.14 Sample Output (DOS mode)

The output window can also be included within the IDE environment. To include the output
window, click on the Window menu and select Output (see Figure A.15).

143 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Figure A.15 Showing Output Window

Figures A.16 and A.17 show sample an equivalent output window included within the IDE
environment.

Figure A.16
Sample
Output 1

144 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Figure A.17 Sample Output 2

9. Closing Current Source File

To close current source file, press ALT-F3 or click on Window menu and select Close or Close All
(see Figure A.18).

Figure A.18 Close Window Menu

145 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

10. Opening Existing Source File

To open existing source file, click on File menu and select Open (see Figure A.18).

Figure A.18 Open File Menu

A dialog box will be shown that will allow the user to select from the currently saved files. Select
a file and click on Open button (see Figure A.19).

Figure A.19 Opening Source Files

146 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

11. Exiting Turbo C++ IDE

To exit Turbo C++ IDE, press ALT-X or click on File menu and select Quit (see Figure A.20).

Figure A.20 Exit Turbo C++

147 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Reference List:

(2002, January 2). Retrieved April 12, 2013, from Gibmonks:


http://www.gibmonks.com/c_plus/ch04lev1sec4.html

Alex. (2007, June 15). cpp-tutorial. Retrieved April 15, 2013, from Learncpp.com: http://www.learncpp.com/cpp-
tutorial/36-logical-operators/

Bronson, G. J. (1999). C++ for engineers and scientists. Singapore: Brooks/Cole.

Carroll, L. (1865). Alice in Wonderland. England: MAcmillan.

qwewqe. (2000). weewwe. dfdfd: sddf.

(2002, January 2). Retrieved April 12, 2013, from Gibmonks:


http://www.gibmonks.com/c_plus/ch04lev1sec4.html

Alex. (2007, June 15). cpp-tutorial. Retrieved April 15, 2013, from Learncpp.com:
http://www.learncpp.com/cpp-tutorial/36-logical-operators/

Bronson, G. J. (1999). C++ for engineers and scientists. Singapore: Brooks/Cole.

Carroll, L. (1865). Alice in Wonderland. England: MAcmillan.

Balci, Osman, Gilley, William S., Adams, Robin J., Tunar, Emre, Barnette, Dwight N. (n.d). Definition of Algorithms.
Online Interactive Modules for Teaching Computer Science Retrieved from
http://courses.cs.vt.edu/csonline/Algorithms/Lessons/index.html

Computer Basics Guide (2009). Types of Computers. Computer Basics for Beginners Retrieved May 5, 2013from
http://www.computerbasicsguide.com/basics/types.html

Discovering Computers (2002). Chapter 1 – Introduction to Computers. Retrieved May 5, 2013from


http://www.slideshare.net/ZOulKapunk/chapter-1introductiontocomputers3165

Fabien Gandon (1999). Types of Computers. Computer's Funadamentas Course. BTEc Higher National Certificate
in Business Information Technology at Watford University Retrieved May 5, 2013from
http://www.cs.cmu.edu/~fgandon/lecture/uk1999/computers_types/

Jumani, Nasir (2009). Computing Fundamentals Module Lesson 2 – Computer Hardware. Computer Literacy
BASICS Retrieved May 5, 2013from http://www.slideshare.net/nasirjumani/power-point-lesson-02

Oak, Manali (2011). Different Types of Computers Retrieved May 5, 2013from


http://www.buzzle.com/articles/different-types-of-computers.html

Regional Office of Education #3 (n.d.). Parts of Computers. Introduction to Computers Retrieved May 5,
2013from http://www.fayette.k12.il.us/99/Intro2Comp/parts.html

Slideshare (2011). Basic Computer Parts. Retrieved May 5, 2013from http://www.slideshare.net/dkeppner/basic-


computer-parts

148 | P a g e
CC 101. Computer Programming 1 SY 2017-2018

Slideshare (2010). Introduction to Computers Retrieved May 5, 2013 from


http://www.slideshare.net/Sammy17/chapter-1-introduction-to-computers-4170691

Slideshare (2007). Hardware of Personal Computers Retrieved May 5, 2013from


http://www.slideshare.net/ipwk/lesson-2-ppt-v6

Wikipedia - The Free Encyclopedia (2013). Mechanical Computer Retrieved From


http://en.wikipedia.org/wiki/Mechanical_computer

149 | P a g e

You might also like