0% found this document useful (0 votes)
31 views196 pages

Eaac0203 LM03

Uploaded by

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

Eaac0203 LM03

Uploaded by

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

LM03-EAAC

0203

Learning Module 03

Computer
Programming Using C
Language

Knowledge Area Code : EAAC


Course Code : EAAC0203
Learning Module Code : LM03-EAAC0203
Course LM03-EAAC
Packet

01 0203

Module Overview
Module Overview

Introduction

Learning Module 3, Computer Programming Using C Language, is an introduction to


computer programming concepts and C Language programming that will be used in the whole
course of Computer Fundamentals and Programming. Computer programming life cycle,
programming languages, flowcharting and pseudocode will be tackled and applied to give the
students an experience on how important and useful they are in creating solutions for a
computer programming problem. CppDroid and TurboCDroid for Android gadgets, CppCode
for Apple gadgets, and Microsoft Visual C++, TurboC and DosBox for PCs and laptops will be
used as the programming software to demonstrate the coding and testing the solution phase
of the programming life cycle. Data Types, Selection Structures, Repetition Structures and
Functions and Arrays will also be discussed to demonstrate how to manipulate data and
processes inside a computer program. Also, graphics manipulation will be included in the
discussion to provide students with a basic know-how in creating an innovative computer
program. Computer programs can be useful in analyzing the data from the work and research
accomplished by the experts in the field of engineering. Examples and research are given for
the topic of C Language to further the students’ technical knowledge of computer
programming.

• Topic 01: Introduction to Computer Programming


• Topic 02: C Programming
• Topic 03: Selection Structures
• Topic 04: Repetition Structures
• Topic 05: Function and Arrays
• Topic 06: Graphics Manipulation

Learning Outcomes

The following are the learning outcomes of this module:


1. Ability to manipulate the different C language commands and functions for different
applications.
2. Create a gender-inclusive complex program with engineering applications.

Minimum Technical Skills Requirement

Technical Skills required for the students are the following:


• Basic Computer Operation
• Basic Computer Programming

Learning Management System

BSEE 1C Google Classroom Link: https://classroom.google.com/c/NjYzNDQ1NDE2NTAx?cjc=e55hvj2


BSEE 1D Google Classroom Link: https://classroom.google.com/c/NjYzNDQzMDU2MTI0?cjc=fbfpl6c

Course Module: Computer Programming 418


Course LM03-EAAC
Packet

01 0203

Duration

• Topic 01: Introduction to Computer Programming = 3 hours


Module Overview

• Topic 02: C Programming = 6 hours


• Topic 03: Selection Structures = 12 hours
• Topic 04: Repetition Structures = 12 hours
• Topic 05: Function and Arrays = 12 hours
• Topic 06: Graphics Manipulation = 12 hours

Delivery Mode

Learning Module 3, Computer Programming Using C Language, will be delivered via onsite
learning (face-to-face), online learning (synchronous) and offsite learning (asynchronous).

Module Requirement with Rubrics

The following criteria and the corresponding percentage shall be used to assess the
collaborative learning exercises and laboratory reports as an assessment tool or task.

Criteria Description %
Able to execute calculations correctly by hand and
Calculation apply appropriate mathematical 50%
equations/formulas.
Solution All the answers are correct and properly labeled. 20%
Written work is presented neatly and
Neatness 10%
professionally.
Document Submitted work conforms to the prescribed
10%
Formatting format.
Work is submitted on or before the specified date
Timeliness 10%
and time.
TOTAL 100%

Course Module: Computer Programming 419


Course LM03-EAAC
Packet

01 0203

Pre-Assessment
Computer Programming Using C Language
Pre-Assessment

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out in an A4 bond paper, write your answers in the space
provided and post a PDF File or captured/scanned image of your paper with cover page in our
Google Classroom. Erasures and abbreviations mean wrong. Keep your work clean and avoid
erasures. Use of pencil is prohibited. Use only a blue ballpoint pen. (20 points)

1. ____________________ is the developer of C Language.


2. ____________________ is used to store many values in a single variable.
3. ____________________ has the scope of a local variable but the lifetime of global variable.
4. ____________________ is used to repeat the process based on the condition set in the
program.
5. ____________________ is the highest and lowest value that a data type can represent.
6. ____________________ is a symbol that represents a specific action.
7. ______________________________ it combines comparisons in a single if or else if
statement.
8. ____________________ is the error encountered during the execution of a computer
program.
9. ____________________ is a C++ rule for determining which operation is performed first.
10. The conditional operator requires ____________________ operands.
11. ____________________ is the visual representation of the algorithm.
12. ____________________ is a way of referring to data and reserving memory necessary to
store that data.
13. ____________________ is the program that translates the C program source code into
machine code.
14. ____________________ is the grammar followed by the computer programming languages.
15. ____________________ has the lowest priority when arithmetic, logical, and relational
operators are combined.
16. ____________________ is a group of statements that together perform a task.
17. ____________________ is a code statement that has a value that needs to be evaluated when
the program runs.
18. Comparison is made using ______________________________.
19. ____________________ is the function used to initializes the graphics systems of TurboC.
20. ____________________ is used to manipulate the process by using questions answerable by
true or false inside the program.

Course Module: Computer Programming 420


Course LM03-EAAC
Packet

01 0203

Learning Module 03

Computer
Programming Using C
Language
Course Packet 01

Introduction to Computer
Programming

Knowledge Area Code : EAAC


Course Code : EAAC0203
Learning Module Code : LM03-EAAC0203
Course Packet Code : LM03-EAAC0203-01

Learning Module: Purposive Communication 3


Course LM03-EAAC
Packet

01 0203

Course Packet 01
Course Packet 01

Introduction to Computer Programming


Introduction

This course packet introduces the students to the concepts of computer programming,
programming cycle, and algorithm development. Computer programming languages will be
discussed also with flowcharting and pseudocode to familiarize the student in creating
solutions for programming problems. Different programming problems will be discussed to
give students hands-on experience in computer programming solving.

Objectives

At the end of the course packet, the students will be able to:
• Explain the process of the programming cycle and algorithm development.
• Create a flowchart and pseudocode of different gender-responsive programming
problems.

Learning Management System

BSEE 1C Google Classroom Link: https://classroom.google.com/c/NjYzNDQ1NDE2NTAx?cjc=e55hvj2


BSEE 1D Google Classroom Link: https://classroom.google.com/c/NjYzNDQzMDU2MTI0?cjc=fbfpl6c

Duration

• Topic 01: Introduction to Computer Programming = 3 hours


(2 hours self-directed learning and 1 hour assessment)

Delivery Mode

Course Packet 1, Introduction to Computer Programming, will be delivered via onsite learning
(face-to-face), online learning (synchronous) and offsite learning (asynchronous).

Assessment with Rubrics

The following criteria and the corresponding percentage shall be used to assess the
collaborative learning exercises and laboratory reports as an assessment tool or task.

Criteria Description %
Able to execute calculations correctly by hand and
Calculation apply appropriate mathematical 50%
equations/formulas.
Solution All the answers are correct and properly labeled. 20%
Written work is presented neatly and
Neatness 10%
professionally.

Course Module: Computer Programming 422


Course LM03-EAAC
Packet

01 0203

Document Submitted work conforms to the prescribed


10%
Formatting format.
Work is submitted on or before the specified date
Course Packet 01

Timeliness 10%
and time.
TOTAL 100%

Requirement with Rubrics

Each student is required to accomplish the collaborative learning exercise and laboratory report
found after reading the course packet. The accomplished collaborative learning exercise and
laboratory report should be posted or submitted at the Google Classroom stream page of the
class on the scheduled date to be given by the faculty in charge.

Readings

1. C++ Demystified by Jeff Kent


2. C++ Through Examples by Dr. Palaniappan Sellappan
3. C# Programming from Problem Analysis to Program Design by Barbara Doyle
4. Turbo C/C++ The Complete Reference Second Edition by Herbert Schildt
5. https://www.tutorialspoint.com/cprogramming/index.htm
6. https://www.w3schools.in/c-tutorial/intro/

Course Module: Computer Programming 423


Course LM03-EAAC
Packet

01 0203

Introduction
Key Points:

Computer programming is a way of giving computers


Course Packet 01

• Computer
instructions about what they should do next. These instructions programming is the act
of writing computer
are known as code, and computer programmers write code to programs, which are a
solve problems or perform a task. The end goal of computer sequence of
instructions written
programming is to create something: that could mean anything using a programming
from a web page, or a piece of software, or even just a pretty language to perform a
specified task by the
picture. It is why computer programming is often described as
computer.
a mix between art and science; it’s technical and analytical, yet • The source code of a
creative at the same time. program is written in
one or more languages
that are intelligible to
Lesson Proper programmers, rather
than machine code,
which is directly
Computer Programming executed by the central
processing unit.

Computer programming (often shortened to Definition of Terms:


programming or coding), sometimes considered a branch of Computer
applied mathematics, is the process of writing, testing, Programming. Computer
programming is the
debugging, and maintaining the source code of computer process of designing and
programs using computer programming language to perform a building an executable
computer program to
specified task by the computer. The purpose of programming is accomplish a specific
to create a program that exhibits a certain desired behavior computing result or to
perform a specific task.
(customization).
Computer Program.
Computer program is a
collection of instructions
A computer program is a detailed, step-by-step set of
that can be executed by a
instructions that are executed by a computer to perform a specific computer to perform a
task or solve a specific problem. It sequences the tasks a user specific task.
Debugging. Debugging is
wants to be done and produces the results of output needed. The the process of finding and
set of rules or instructions that tells the computer what to resolving bugs (defects or
problems that prevent
perform is done or written through a variety of programming correct operation) within
languages. computer programs,
software, or systems.
Source Code. Source
A programmer is a person who designs a program. It code is any collection of
code, with or without
converts problem solutions into instructions for the computer. comments, written using a
The programmer designs the program decides which of the human-readable
programming language,
programs or set of instructions to use and tests the program to usually as plain text.
see if it is working as designed.

Course Module: Computer Programming 424


Course LM03-EAAC
Packet

01 0203

A programming language is a set of words, symbols, and


codes that enable humans to communicate with computers. Key Points:

There is a lot of programming languages that exist today. Some • Programming


Course Packet 01

of it has its standards in writing. Some examples are C, C++, C#, languages are used in
computer programming
Java, and Perl. The process of creating program code often to implement
requires expertise in program algorithm, design, and logic. Just algorithms. Most
programming
like human languages, programming languages also follow languages consist of
grammar called syntax. Certain basic program code elements are instructions for
computers.
common for all programming languages. The most important
• The description of a
basic elements for programming languages are Programming programming language
is usually split into the
Environment, Data Types, Variables, Keywords, Logical and
two components of
Arithmetical Operators, If else conditions, Loops, Numbers, syntax (form) and
Characters and Arrays, Functions, and Input and Output semantics (meaning).

Operations. Definition of Terms:

Algorithm. Algorithm is a
An algorithm is a sequence of unambiguous, finite, and finite sequence of well-
ordered instructions to be followed to solve a problem. Usually defined, computer-
implementable
implements a program algorithm. The instruction sequence instructions, typically to
itself must be finite, not the number of steps taken. The programs solve a class of problems
or to perform a
are usually divided into smaller parts (modules) so that the computation.
algorithm complexity of each of the parties is less than the full Programming
Language. Programming
program, which helps the development of the program. language is a formal
According to Niklaus Wirth, a program consists of algorithms language comprising a set
of instructions that
and data structure. Various techniques have been proposed for produce various kinds of
the program whose goal is to improve the process of creating and output.
Semantics. Semantics is
maintaining software.
the field concerned with
the rigorous mathematical
study of the meaning of
Programming Languages
programming languages.
Syntax. Syntax of a
A programming language is an artificial language that computer language is the
set of rules that defines
can be used to control the behavior of a machine, particularly a the combinations of
computer. Programming languages are used to facilitate symbols that are
considered to be correctly
communication about the task of organizing and manipulating structured statements or
information, and to express algorithms precisely. There are two expressions in that
language.
kinds of programming languages which are low-level
programming language and high-level programming language.
Low-level programming language is consisting of First
Generation and Second Generation. High-level programming
language is consisting of Third, Fourth, and Fifth Generation

Course Module: Computer Programming 425


Course LM03-EAAC
Packet

01 0203
Key Points:
languages.
• Machine language is
Low-Level Programming Languages made up of a series of
Course Packet 01

0's and 1's. Each 0 or 1


is known as a bit (short
Low-level programming languages are so named for binary digit). A
group of eight bits,
because they are closer to machine language than to human known as a byte,
language; that is, it is easier for the machine (computer) to represents one
character (i.e., a
understand them than it is for humans. The lowest level of number or a letter).
language par excellence is the machine code. This was followed • Assembly language is
not a single language,
by the assembly language, as when programming in assembler but rather a group of
is working with the memory registers of the computer directly. languages because
each processor family
has its own assembly
Low-level programming languages are sometimes language.
divided into two categories which are the first generation and
Definition of Terms:
second generation.
1. First Generation or Machine Language is a language system Assembler. Assembler
creates object code by
that is executed directly by a computer processing unit. The translating assembly
program is represented by 1s and 0s. Machine language may instruction mnemonics
into opcodes.
be regarded as an extremely hardware-dependent Assembly Language.
programming language. Assembly language is a
low-level programming
2. Second Generation or sometimes called Assembly language for a computer,
Language. Instead of using 1s and 0s, assembly language microcontroller, or other
programmable device, in
uses mnemonic codes. Mnemonic codes are abbreviations which each statement
that are easy to remember. Each type of computer has its corresponds to a single
machine code instruction.
very own assembly language. Machine Language.
Example: Machine language,
sometimes referred as
ORG 100h machine code or object
MOV AL, var1 code, is a collection of
binary digits or bits that
MOV BX, var2
the computer reads and
RET interprets.
Mnemonic. A mnemonic
VAR1 DB 7
is a symbolic name for a
var2 DW 1234h single executable
machine language
instruction (an opcode),
and there is at least one
opcode mnemonic defined
for each machine
language instruction.

Course Module: Computer Programming 426


Course LM03-EAAC
Packet

01 0203

Key Points:
Course Packet 01

• High-level
programming
languages such as
COBOL, FORTRAN,
BASIC, PASCAL, PL/1,
and C are described
high-level because they
are closer to human
language than to
Figure 246: Compiled Machine Code of the Sample Assembly Code machine language.

Definition of Terms:
High-Level Programming Languages
BASIC. Beginners' All-
purpose Symbolic
High-level programming languages feature is to express Instruction Code is a
algorithms in a way human does, rather than executing like family of general-purpose,
high-level programming
machines. The limitation of the high-level language is that it languages whose design
requires some programming skills to perform the logical philosophy emphasizes
ease of use.
sequence of instructions. The very high-level languages were COBOL. COmmon
created so that users could solve this common problem of data Business-Oriented
Language is a compiled
processing easier and faster. The main advantage of high-level English-like computer
languages over low-level languages is that they are easier to programming language
designed for business
read, write, and maintain. Programs written in a high-level
use.
language must be translated into machine language by a FORTRAN. FORmula
TRANslator is a general-
compiler or interpreter.
purpose, compiled
imperative programming
High-level programming languages are sometimes language that is especially
suited to numeric
divided into three categories: third generation, fourth computation and scientific
generation, and fifth generation. computing.
PASCAL. Pascal is an
1. Third Generation Language (3GL) or High-Level Language imperative and procedural
transformed programming in the early 1960s. It is the first programming language
intended to encourage
to use the true English language which is much easier to use good programming
compared to other low-level languages. If assembler is used practices using structured
programming and data
by the assembly language, third-generation languages use structuring.
the translator to convert the program into a machine PL/I or PL/1.
Programming Language
language. The third generation languages are portable, the One is a procedural,
object code created for one type of system can be translated imperative computer
programming language for
to another different type of system. Some examples are scientific, engineering,
FORTRAN, COBOL, Basic, Pascal, C, C++, and Java. business and system
programming.
2. Fourth Generation Language (4GL) or Very High-Level
Language is closer to human languages than a typical high-

Course Module: Computer Programming 427


Course LM03-EAAC
Packet

01 0203

level programming language. It further simplifies the third-


generation languages (3GL) because there is a reduction in
the number of instructional statements. One hundred (100)
Course Packet 01

lines of instructions in 3GLs can be reduced to five (5) to


twenty (20) lines of instructions in 4GLs. More 4GLs are used
to access databases such as database queries, report
generators, data manipulation, analysis and reporting, web
development, and general-purpose languages. 4GLs are
more user-friendly because of the use of icons, graphical
interfaces, and the use of English-like words and phrases.
Some examples are Visual Basic and other Visual
environments.
3. Fifth Generation Language or Natural Language has a closer
resemblance to the English language. It has the capability to
translate human instructions into code that a computer
understands. If it gets confused with the user’s instructions,
it asks for further explanations. Fifth generation languages
are based on solving problems using constraints given to the
program, rather than using an algorithm written by a
programmer. This way, the programmer only needs to
worry about what problems need to be solved and what
conditions need to be met, without worrying about how to
implement a routine or algorithm to solve them. Fifth
generation languages are used mainly in artificial
intelligence and neural networks.

Procedural and Non-Procedural Languages

Procedural Languages

Programming languages that are considered procedural


uses a series of instructions or statements which are sequential
from the beginning to the end. This means that the execution of
instructions is line by line and it is terminated after the last
instruction. Examples of procedural languages are BASIC,
COBOL, Pascal, FORTRAN, C, and PL/1.

Course Module: Computer Programming 428


Course LM03-EAAC
Packet

01 0203

Non-Procedural Languages

Non-procedural languages are considered object-


Course Packet 01

oriented programming languages. They are event-driven which


means that a programmer selects an event that needs to occur
before the instruction or statements is executed. It is different
from procedural language since statements are not executed line
per line instead a series of instructions are executed as a whole
when an event occurs. Examples of events are click, double click,
drag and drop, mouse over, and other events. Examples of non-
procedural languages are Visual Basic, C++, Java, and Delphi.

Programming Life Cycle

A computer is a problem-solving tool. Once it is


properly provided with a valid program, the computer becomes
self-operational, that is, it requires no human intervention
during processing. To use this tool effectively, the programmer
usually has to perform the following set of well-defined steps:
1. Identifying the problem. It is the first step in creating a
program. It involves determining the requirements of the
program to be able to come up with a suitable programming
solution.
2. Planning the Solution. There are two ways of planning the
solution to a problem, they are drawing a flowchart and
writing pseudocode. The flowchart is a graphical
representation of the step-by-step instruction to be done in a
program while pseudocode is listing down the set of
instructions to be used in the program. These two
approaches are not executable in a programming language.
3. Coding the Program. Code the program with the use of a
chosen programming language. If human language follows
grammar in writing and speaking, programming languages
have their own set of rules to follow, this is called syntax.
Violation of the rule set by the programming language used
in a certain program will produce an error called syntax
error. One of the common causes of syntax error is a
misspelling.
4. Testing the Program. After coding the program, it is

Course Module: Computer Programming 429


Course LM03-EAAC
Packet

01 0203

important to test if it is running. If it runs properly, then it is


free from a syntax error, however, there will be instances that
it does not meet the requirements of the program. Testing
Course Packet 01

the program involves three phases:


1. Desk checking is the phase when the programmer just
mentally traces or checks the logic of the program to
make sure that it's error-free.
2. Translation is the phase when the programming
language uses a translator to ensure that the
programmer did not violate any language rules by the
chosen programming language. This program translates
the program line by line to locate any syntax error.
3. Debugging means detecting, locating, and correcting
bugs. In programming, error or mistakes are called
bugs. In debugging phase, the programmer runs the
program and uses dummy data or test data. Then, the
programmer checks the flow of the program if its logic
is error-free and if it meets the requirements of the
specified program.
5. Documentation. In this step, the programmer makes a
detailed description of how the program was created. It
contains a brief narrative process undergone by the program,
from the identification of the problem, planning of the
solution through flowcharting and pseudocode, coding of
the program up to the testing results. Codes used for the
program are also included in this documentation as a
reference for the next programmer who will upgrade the
designed program.

Course Module: Computer Programming 430


Course LM03-EAAC
Packet

Course Packet 01 01 0203

Figure 247: Programming Life Cycle

Algorithm

An algorithm is a list of instructions for carrying out


some process step by step. Algorithms executed by a computer
can combine millions of elementary steps, such as additions and
subtractions, into a complicated mathematical calculation. If an
algorithm is devised for a process, it can usually be done so in
many different ways. Some properties of the algorithm are:
• Finiteness. There is an exact number of statements to be
executed and has its ending.
• Absence of Ambiguity. Statements are clearly described and
defined.
• Sequence of Execution. The sequence of statements is done
from top to bottom.
• Input and Output. Unknown values must be identified and
exact output must be defined.
• Effectiveness. The solution to the problem must be correct.
• Scope of Definition. Identify the scope of the problem.

Pseudocode

Pseudocode specifies the steps of the algorithm using the


language of control structure. It is a compact and informal high-
level description of a computer programming algorithm that
uses the structural conventions of some programming language
but is intended for human reading rather than machine reading.

Course Module: Computer Programming 431


Course LM03-EAAC
Packet

01 0203

Example 1:
If student’s grade is greater than or equal to 60
Print “Passed”
Course Packet 01

Else
Print “Failed”
Example 2:
Give variable num1 a starting value of 5
Give variable num2 a starting value of 10
Add 7 to num2
Store the value num1 times num2 in variable num3
Store the value num2 minus num1 in num2
Output num1, num2, and num3

Flowchart

A flowchart is a graphical or visual representation of the


algorithm of the program. It was introduced by Frank Gilberth
in 1921, and they were called “Process Flow Chart”.

A flowchart is a diagram representing the logical


sequence in which a combination of steps or operations is to be
performed. It consists of labeled geometrical symbols that are
interconnected to provide a pictorial representation of a data
processing procedure. It also can be used to depict the hardware
associated with a computer information system.

Types of Flowcharts

The flowchart can be categorized into four main types.


1. Document Flowchart. It shows controls over a document
flow through a system, such as a payroll information,
internal memos, and office mail. The flowchart shows how
document passes from one part of the company to another.
It does contain minimal details.
2. System Flowchart. It shows controls on how the entire
system works by demonstrating how data flows and what
decisions are made to control it. A system flowchart
combines all the resources with the related processes.
3. Data Flowchart. It shows controls over a data-flow system.

Course Module: Computer Programming 432


Course LM03-EAAC
Packet

01 0203

It illustrates how data passes through a system. It tracks the


origin and end of data. It is more concerned with the
movement of data more than how data is processed.
Course Packet 01

4. Program Flowchart. It shows controls over how a program


works within a system. These flowcharts show any and all-
user interaction pathways. Program charts are large and
complex.

Flowchart Symbols

Actual program statements are written inside the


appropriate symbols. Flowchart symbols conform to the
International Organization for Standardization (ISO) and
American National Standard Institute.
1. Input/Output Symbol (Parallelogram). It represents an
instruction to an input or an output device.
2. Processing Symbol (Rectangle). It is used to represent a
group of program instructions that perform a processing
function of the program.
3. Decision Symbol (Diamond). It denotes a point in the
program where more than one path can be taken. It is also
used to document points in the program where, based upon
variable conditions, a branch to alternative paths is possible.
The particular path that is chosen depends on the answer to
a question or the result of a test that is inserted in the symbol.
4. Preparation Symbol (Hexagon). It is used to represent an
instruction or group of instructions that will alter, or modify
a program’s course of execution. It is commonly used to
specify operations such as control, index register,
initialization, switch setting, and in indicating loops.
5. Terminal Symbol (Oval). It is used to designate the
beginning and the end of a program, or a point of
interruption. It can also be used elsewhere in the flowchart
for specifying error conditions, such as parity error checks or
detection of invalid characters.
6. Predefined Process Symbol (Rectangle with Two Vertical
Bars). It is a specialized process symbol that represents a
named operation or programmed step not explicitly detailed
in the program flowchart. As a subroutine symbol, it can be

Course Module: Computer Programming 433


Course LM03-EAAC
Packet

01 0203

used when a procedure needs to be repeated several times.


7. On-page Connector (Small Circle). It is a non-processing
symbol that is used to connect one part of a flowchart to
Course Packet 01

another without drawing flow lines. It denotes an entry or


an exit from another part of the flowchart and is also used to
change the reading sequence of a flowchart on the same
page. On-page connectors conserve space by keeping related
blocks near one another, reducing the number of flow lines
in complex programs, and eliminating cross lines from
taking place. It also aids in developing a clearer, better
organized, and more simplified flowchart.
8. Off-page Connector (Small Pentagon). It is used instead of
the on-page connector to designate entry to or exit from a
page when a flowchart requires more than one page. It is
commonly used in complex flowcharts which often require
a detailed diagram extending over several pages.
9. Flow Lines (Horizontal/Vertical Lines). It is used to show
the reading order or sequence in which flowchart symbols
are to be read.
10. Flow Direction Indicators (Arrowheads). It is used to show
the direction of processing or data flow. It is added to flow
lines if a flowchart appears confusing in its layout.

Table 47. Flowchart Symbols


Flowchart Symbol Name Geometric Shape

Input/Output

Process

Decision

Preparation

Terminal

Predefined Process

On-Page Connector

Course Module: Computer Programming 434


Course LM03-EAAC
Packet

01 0203

Off-Page Connector
Course Packet 01

Flow Lines

Flow Direction
Indicators

START

GO TO WORK

A
TAKE A
COFFEE
BREAK

IS IT TIME
Y
TO GO GO HOME
HOME?

N B

STOP
N IS THE
BOSS
A LOOKING?

DO SOME
B
WORK

Figure 248: Flowchart Example

Flowchart Notations

Flowchart notations are symbols used inside flowchart


symbols to denote process or operation.

Table 48. Flowchart Notations


Notation Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
** or [ or  Exponentiation
: Comparison
() Grouping

Course Module: Computer Programming 435


Course LM03-EAAC
Packet

01 0203

| Logical Or
& Logical And
= or EQ Equal to
Course Packet 01

> or GT Greater than


< or LT Less than
< > or ≠ or NE Not Equal to
≥ or GE Greater than or Equal to
≤ or LE Less than or Equal to
% Modulus
Y Yes
N No
EOF End of File

Illustrative Problems on Simple Logic Flow

In creating a program flowchart, follow the step of the


programming life cycle. In identifying the problem, from the
problem identify the given data, data that are specified or
implied in the problem, input, data that will come from the
program user, required, data to be processed or computed, and
output, data that will be displayed on the screen. Also, data in
the flowchart should be indicated using variables, which are the
storage of data in a computer program. Take note, lowercase
letters used as the variable is different from uppercase letters.
Data that are not stored in variables cannot be displayed on the
output screen.
1. The radius of a circle is equal to one unit. Draw a flowchart
to compute the corresponding area of the circle and print out
the value of the radius and the area.
Identifying the Problem
Given: variable R for radius → R = 1
variable pi for pi of circle → pi = 3.14159
Input: None
Required: variable A for area of circle → A = ?
Output: R, A

Course Module: Computer Programming 436


Course LM03-EAAC
Packet

01 0203

Planning the Solution


Flowchart
Course Packet 01

Start

R=1, pi=3.14159

A = pi*R**2

Print R, A

Stop

Pseudocode
Begin
Set R=1, pi=3.14159
A=pi*r**2
Print R, A
End
2. Given three numbers A, B, C. Draw a flowchart to compute
and print out the sum, the average, and the product of these
values.
Identifying the Problem
Given: None
Input: numbers A, B, C
Required: variable S for sum → S = A+B+C
variable a for average → a = (A+B+C)/3
variable P for product → P = A*B*C
Output: S, a, P

Course Module: Computer Programming 437


Course LM03-EAAC
Packet

01 0203

Planning the Solution


Flowchart
Course Packet 01

Start

Print “Input 3 numbers”


Input A, B, C

S = A+B+C
a = (A+B+C)/3
P = A*B*C

Print S, a, P

Stop

Pseudocode
Begin
Print “Input 3 numbers”
Read A, B, C
S = A+B+C
a = (A+B+C)/3
P = A*B*C
Print S, a, P
End
3. The ABC Manufacturing Company plans to give a year-end
bonus to each of its employees. Draw a flowchart that will
compute the bonus of an employee. Consider the following
criteria: If the employee’s monthly salary is less than 1,000.00
pesos, the bonus is 50% of the salary; for employees with
salaries 1,000.00 pesos and above, the bonus is 1,000.00. Print
out the name and corresponding bonus of the employee.
Identifying the Problem
Given: None
Input: variable S for salary → S
variable N for name → N
Required: variable B for bonus → B = ?

Course Module: Computer Programming 438


Course LM03-EAAC
Packet

01 0203

S < 1000 then B = S*0.5


S ≥ 1000 then B = 1000
Output: N, B
Course Packet 01

Planning the Solution


Flowchart

Start

Print “Input name and salary”


Input N, S

Is N
B = 1000
S<1000?

Y
A
B = S*0.5

Print N, B

Stop

Pseudocode
Begin
Print “Input name and salary”
Input N, S
If S<1000 Then
B = S*0.5
Else
B = 1000
End If
Print N, B
End
4. Given two numbers X and Y. Draw a flowchart to determine
the difference between X and Y. If X-Y is negative, compute

Course Module: Computer Programming 439


Course LM03-EAAC
Packet

01 0203

R= X+Y; if X-Y is zero, compute R = 2X+2Y; and if X-Y is


positive, compute R = XY. Print out the values of X, Y, and R.
Identifying the Problem
Course Packet 01

Given: None
Input: numbers X, Y
Required: R = ?
X – Y < 0 then R = X+Y
X – Y = 0 then R = 2*X+2*Y
X – Y > 0 then R = X*Y
Output: X, Y, R
Planning the Solution
Flowchart

Start

Print “Input 2 numbers”


Input X, Y

Is Y
R = X+Y
X-Y<0?

N
A

Is Y
R = 2*X+2*Y
X-Y=0?

N
A
R = X*Y

Print X, Y, R

Stop

Course Module: Computer Programming 440


Course LM03-EAAC
Packet

01 0203

Pseudocode
Begin
Print “Input 2 numbers”
Course Packet 01

Input X, Y
If X – Y<0 Then
R = X+Y
Else If X – Y=0 Then
R = 2*X+2*Y
Else
R = X*Y
End If
Print X, Y, R
End

Flowchart Tracing

Flowchart tracing is used to determine the correctness of


logic flow within any given flowchart, it will usually require
some amount of tracing and testing. Tracing will provide a
clearer understanding of the processing steps involved. It will
usually require the use of actual test data values.

The first step is to have a list of variable names used


which will hold different values during the processing operation.
Begin tracing the flowchart with the first instruction and
continue by following the appropriate flow lines and flow
direction indicators. If the instruction is in a process box, a
calculator may be needed to evaluate an arithmetic expression
contained in it. If the instruction is in a decision box, the
expression written in it has to be evaluated.

Course Module: Computer Programming 441


Course LM03-EAAC
Packet

01 0203

Collaborative Learning Exercise 7


Introduction to Computer Programming
Collaborative Learning Exercise 7

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with a cover page in our Google Classroom.
Keep your work clean and avoid erasures. Use of pencil is prohibited. Use only a blue ballpoint
pen.

Create the flowchart and pseudocode that will determine if the voter can vote in the Barangay
Election, in the Sangguniang Kabataan Election, or not. If the age of the voter is 12 to 17, then
he/she can vote in the Sangguniang Kabataan Election. If the age of the voter is 18 and above,
then he/she can vote in the Barangay Election. Otherwise, the voter cannot vote. Print out the
name of the voter, age, and the message “Congratulations, you can vote in the Sangguniang
Kabataan Election!” or “Congratulations, you can vote in the Barangay Election!” for those that
can vote and “Sorry, you cannot vote!” for those who cannot vote. (30 points)

Course Module: Computer Programming 442


Course LM03-EAAC
Packet

01 0203

Laboratory Report 6
Introduction to Computer Programming
Laboratory Report 6

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with a cover page in our Google Classroom.
Keep your work clean and avoid erasures. Use of pencil is prohibited. Use only a blue ballpoint
pen.

Create the flowchart and pseudocode that prompts a user to enter a number. After the number
has been entered, display one of the following messages and the number entered. (40 points)

Numbers Message
Below 6 Too Small
6 – 10 Small
11 – 20 Medium
21 – 30 Large
Above 30 Too Large

Course Module: Computer Programming 443


Course LM03-EAAC
Packet

01 0203

Practical Exam 6
Introduction to Computer Programming
Practical Exam 6

(Topics Covered: All the topics in Course Packet 01 of Learning Module 03)

Remember:
The Practical Exam will be administered face-to-face. You are given an hour to answer this
practical exam. This is an individual assessment, therefore, individual submission of answer to
is required. Cheating in any form is highly discouraged.

Course Module: Computer Programming 444


Course LM03-EAAC
Packet

01 0203

References
C Tutorial. (n.d.). Retrieved from W3schools.in: https://www.w3schools.in/c-tutorial/intro/
References

C++ Language. (2000). Retrieved June 27, 2016, from cplusplus.com:


http://www.cplusplus.com/doc/tutorial/

Doyle, B. (2014). C# Programming From Problem Analysis to Program Design Fourth Edition. New
Tech Park, Singapore: Cengage Learning Asia Pte Ltd.

Kent, J. (2005). C++ Demystified. USA: Mc Graw Hill Osborne.

Savitch, W. (1996). Problem Solving with C++ The Object of Programming. California, USA:
Addison-Wesley Publishing Company, Inc.

Schildt, H. (1992). Turbo C/C++: The Complete Reference, Second Edition. California, USA:
Osborne Mc-Graw Hill.

Sellappan, P. (2001). C++ Through Examples. Selangor Darul Ehsan, Malaysia: Federal
Publication Sdn. Berhad.

tutorialspoint. (2020). (Tutorials Point (I) Pvt. Ltd.) Retrieved July 3, 2020, from
https://www.tutorialspoint.com/cprogramming/index.htm

Course Module: Computer Programming 445


Course LM03-EAAC
Packet

01 0203

Learner’s Feedback Form


Learner’s Feedback Form

Name of Student: _____________________________________________________________


Program : _____________________________________________________________
Year Level : ________ Section : _____ Sex at Birth: ___________
Faculty : _____________________________________________________________
Schedule : _____________________________________________________________

Course Packet : Code : _________ Title : __________________________________

How do you feel about the topic or concept presented?


 I completely get it.  I’m struggling.
 I’ve almost got it.  I’m lost.

In what particular portion of this course packet, do you feel that you are struggling or lost?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Did you raise your concern to your instructor?  Yes  No

If Yes, what did he/she do to help you?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

If No, state your reason?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

To further improve this course packet, what part do you think should be enhanced?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

How do you want it to be enhanced?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Course Module: Computer Programming 446


Course LM03-EAAC
Packet

02
01 0203

Learning Module 03

Computer
Programming Using C
Language
Course Packet 02

C Programming

Knowledge Area Code : EAAC


Course Code : BECC0203
Learning Module Code : LM03-EAAC0203
Course Packet Code : LM03-EAAC0203-02

Course Module: Computer Programming 447


Course
Packet
LM03-EAAC

02 0203

Course Packet 02
Course Packet 02

C Programming
Introduction

This course packet introduces the students to the basic concepts of C Language
programming. C language program structure, data types, and variables will be discussed to
familiarize the student in creating a simple C program with input and output data and
reserving memory locations for data manipulation. Different operators such as arithmetic,
relational and logical operators will also be discussed to give students hands-on experience in
C language programming.

Objectives

At the end of the course packet, the students will be able to:
• Explain the different parts of a C language program.
• Differentiate the different data types, variable types, and operators and how it is used in a
C language program.
• Create gender-responsive source code of different programming problems with the help
of a flowchart and pseudocode.

Learning Management System

BSEE 1C Google Classroom Link: https://classroom.google.com/c/NjYzNDQ1NDE2NTAx?cjc=e55hvj2


BSEE 1D Google Classroom Link: https://classroom.google.com/c/NjYzNDQzMDU2MTI0?cjc=fbfpl6c

Duration

• Topic 02: C Programming = 6 hours


(4 hours self-directed learning and 2 hours assessment)

Delivery Mode

Course Packet 2, C Programming, will be delivered via onsite learning (face-to-face), online
learning (synchronous) and offsite learning (asynchronous).

Assessment with Rubrics

The following criteria and the corresponding percentage shall be used to assess the
collaborative learning exercises and laboratory reports as an assessment tool or task.

Criteria Description %
Able to execute calculations correctly by hand and
Calculation apply appropriate mathematical 50%
equations/formulas.
Solution All the answers are correct and properly labeled. 20%

Course Module: Computer Programming 448


Course
Packet
LM03-EAAC

02 0203

Written work is presented neatly and


Neatness 10%
professionally.
Document Submitted work conforms to the prescribed
Course Packet 02

10%
Formatting format.
Work is submitted on or before the specified date
Timeliness 10%
and time.
TOTAL 100%

Requirement with Rubrics

Each student is required to accomplish the collaborative learning exercise and laboratory report
found after reading the course packet. The accomplished collaborative learning exercise and
laboratory report should be posted or submitted at the Google Classroom stream page of the
class on the scheduled date to be given by the faculty in charge.

Readings

1. C++ Demystified by Jeff Kent


2. C++ Through Examples by Dr. Palaniappan Sellappan
3. C# Programming from Problem Analysis to Program Design by Barbara Doyle
4. Turbo C/C++ The Complete Reference Second Edition by Herbert Schildt
5. https://www.tutorialspoint.com/cprogramming/index.htm
6. https://www.w3schools.in/c-tutorial/intro/

Course Module: Computer Programming 449


Course
Packet
LM03-EAAC

02 0203

Introduction
Key Points:

C is a successor of Basic Combined Programming


Course Packet 02

• C language was
Language' (BCPL) called B language which was introduced developed by Dennis
M. Ritchie at the Bell
around the early 1970s. C was invented to write an operating Telephone Laboratories
system called UNIX. The C language was originally designed to in 1972.
• C++ which was an
support procedure-oriented programming. It was subsequently
extension of C
extended to C++ to support object-oriented programming (OOP). language was designed
by Bjarne Stroustrup in
The symbol ++ in C++ indicates that it is an extension of C. Today
1985.
C is the most widely used and popular System Programming
Language. Most of the state-of-the-art software has been Definition of Terms:

implemented using C. ANSI. American National


Standards Institute (ANSI)
is a private non-profit
Lesson Proper organization that oversees
the development of
voluntary consensus
C Language standards for products,
services, processes,
systems, and personnel in
C programming is a general-purpose, procedural, the United States.
imperative computer programming language developed in 1972 C++. C++ is a general-
purpose programming
by Dennis M. Ritchie at the Bell Telephone Laboratories to language created by
develop the UNIX operating system. The language was Bjarne Stroustrup as an
extension of the C
formalized in 1988 by the American National Standard Institute programming language, or
(ANSI). "C with Classes".
Dennis Ritchie. Dennis
MacAlistair Ritchie
C is an imperative language designed to compile (September 9, 1941 – c.
October 12, 2011) was an
relatively straightforwardly, which provides low-level memory
American computer
access. With the gradual increase in the program's popularity, scientist who created the
the language and its compiler have become available on a wide C programming language
and, with long-time
range of platforms, from embedded microcontrollers to colleague Ken Thompson,
supercomputers. With the introduction of the K&R C language, the Unix operating system
and B programming
a new edition of C published in 1978 by Brian Kernighan and language.
Denis Ritchie, several features have been included in the C UNIX. UNIX is a family of
multitasking, multiuser
language. Some of these features are Standard I/O computer operating
(Input/Output) Library, long int - data type, unsigned int - data systems that derive from
the original AT&T Unix,
type, and Compound assignment operators. development starting in
the 1970s at the Bell Labs
research center by Ken
During the late 1980s, C was started to be used for Thompson, Dennis
various mainframe computers, micro, and minicomputers, Ritchie, Brian Kernighan,
Douglas McIlroy, and Joe
which began to get famous. Gradually C got its superset - i.e., Ossanna.

Course Module: Computer Programming 450


Course
Packet
LM03-EAAC

02 0203

C++, which has added features, but it's developed from C with
all its initial concepts. In the beginning, C was used for
developing system applications, such as Database Systems,
Course Packet 02

Language Interpreters, Compilers and Assemblers, Operating


Systems, Network Drivers, and Word Processors. But since it
become the most widely used computer language, other systems
and programming languages are written in C such as Linux
Operating System, PHP, and MySQL.

Figure 249: Dennis Ritchie, Developer of C Language

C language has become popular because it is one of the


early programming languages and still the best programming
language to learn quickly. C language is also reliable, simple,
and easy to use. It is also a structured language and modern
programming concepts are based on C. C can also be compiled
on a variety of computer platforms. Also, universities around
the world preferred to add C programming to their courseware.

C language has a lot of features found in modern


programming languages. C is a robust language with a rich set
of built-in functions and operators. Programs written in C are
efficient and fast. C is highly portable which means programs
once written in C can be run on other machines with minor or no
modification. C is a collection of C library functions and
programmers can also create their own function and add it to the
C library. Lastly, C is easily extensible.

C Language has a lot of advantages over modern

Course Module: Computer Programming 451


Course
Packet
LM03-EAAC

02 0203

programming languages. The most important is C is the


building block for many other programming languages. Second,
programs written in C are highly portable. Third, several
Course Packet 02

standard functions are there (like in-built) that can be used to


develop programs. Fourth, C programs are collections of C
library functions, and it's also easy to add functions to the C
library. And the last one is that the modular structure of the C
program makes code debugging, maintenance, and testing
easier.

Although there are a lot of advantages in using the C


language in designing programs, disadvantages can also be seen
in utilizing it. First, C does not provide Object Oriented
Programming (OOP) concepts. Second, there are no concepts of
Namespace in C. Third, C does not provide binding or wrapping
up of data in a single unit. And lastly, C does not provide
Constructor and Destructor.

Because of these disadvantages, C displays some


limitations during the programming process. First, the C
program is difficult to debug. Second, C allows a lot of freedom
in writing code, and that is why programmers can put an empty
line or white space anywhere in the program. And because there
is no fixed place to start or end the line, so it isn't easy to read
and understand the program. Third, C compilers can only
identify errors or compile-time errors and are incapable of
handling exceptions which are run-time errors. Fourth, C does
not provide data protection. Fifth, it also doesn't feature the
reusability of source code extensively. And last, it does not
provide strict data type checking, such an example is when an
integer value can be passed for the floating datatype.

Anatomy of a C Program

Sample Program 1:

//my first program in C


#include <iostream.h>
using namespace std;

Course Module: Computer Programming 452


Course
Packet
LM03-EAAC

02 0203

int main ()
{
cout << "Hello World!";
Course Packet 02

return 0;
}

Above is an example of a simple program in C++


program. The output of the program above is a simple Hello
World! text in the screen. The code a programmer writes is
referred to as source code, which is saved in a file that usually
has a .cpp extension, standing for C++.

Comment Line

The comment line is part of the source code disregarded


by the compiler and does not have any effect on the behavior of
the program. Its purpose is only to allow the programmer to
insert notes or descriptions embedded within the source code. It
can also be used to include short explanations or observations
within the source code itself. There are two kinds of ways to
insert comments in a C program. The line comment discards
everything from where the pair of slash signs (//) is found up to
the end of that same line. An example is // my first program in
C. The block comment on the other hand discards everything
between the /* characters and the first appearance of the */
characters, with the possibility of including more than one line.
An example is /*Juan Dela Cruz BSIE – 2A Collaborative
Learning Exercise No. 9 C Programming*/.
Syntax:
//comment → line comment
/*comment 1
comment 2
comment 3*/ → block comment

Preprocessor Directive

#include<iostream.h> is an example of an include


directive and it is called a preprocessor directive. A preprocessor
directive lines always begin with a pound sign (#) and is

Course Module: Computer Programming 453


Course
Packet
LM03-EAAC

02 0203

followed by the name of the header file that is enclosed in angle


brackets, < and >. It tells the compiler to include the header file
in the application before compiling the source code. A header
Course Packet 02

file is a file with extension .h which contains C function


declarations and macro definitions to be shared between several
source files. Make sure that all the header file of all the
commands used inside the C program is written using the
preprocessor directive at the top of the program.
Syntax:
#include<headerfile.h>

Namespace

A namespace is not available in a C program but


available in a C++ program. It is used to organize different names
used in programs. The using namespace std; in the sample
program indicates that every name used in the iostream standard
library file is part of a namespace called std.

Function

int main () → function header


{
cout << "Hello World!"; → function body
return 0;
}
The above source code is an example of a function. A
function is a group of related instructions, also called statements,
which together perform a particular task. A program must have
one main function, and only one main function. The main
function is the starting point for every C++ program. If there was
no main function, the computer would not know where to start
the program. If there was more than one main function, the
program would not know whether to start at one or the other.
Syntax:
returntype functionname(argumentlist)
{
statements;
}

Course Module: Computer Programming 454


Course
Packet
LM03-EAAC

02 0203

A function is divided into two parts the function header


and the function body. The function header is consisting of a
return type, a function name, and an argument list. The data
Course Packet 02

type int preceding main is the return type, main is the function
name, and the parentheses (), empty but not always, contain the
argument list. A function header is always followed by an open
curly brace, which begins the function body. Each of the related
instructions, or statements, which belong to the main function
are contained within the body of that function. Each statement
inside the function body always ends with a semicolon. The last
statement is a return statement. The function body must contain
a return statement unless the return type is void, in which case
the return statement is optional. Then the function body ends
with a close curly brace.

cout

cout<<“Hello World!”;
“out” refers to the direction in which cout sends a stream
of data. A data stream may flow in one of two directions. One
direction is input, cin>>, into the program from an outside
source. The other direction is output, cout<<, out from the
program to an outside source.

<< and >> operators are known as the stream insertion


operator. If it is <<, it inserts the information immediately to its
right into the data stream. And if it is >>, it inserts the
information from the outside source immediately to its right
which is commonly an identifier.

return 0; statement

return 0; statement returns a value of zero to the


computer’s operating system. It tells the operating system that
the program ended normally.

Translating the Code for the Computer

Computers don’t understand C++ or any programming

Course Module: Computer Programming 455


Course
Packet
LM03-EAAC

02 0203

language. They understand only machine language. Three


programs are used to translate the source code into an executable
file that the computer can run. They are the preprocessor,
Course Packet 02

compiler, and linker program.

The first to execute during the translation process is the


preprocessor program. The preprocessor is a program that scans
the source code for preprocessor directives such as include
directives. It inserts into the source code all files included by the
include directives.

The second to execute during the translation process is


the compiler program. The compiler is another program that
translates the preprocessed source code into corresponding
machine language instructions, which are stored in a separate
file, called an object file, having a .obj extension. If there is a
syntax error, then the compiler cannot translate the code into
machine language instructions, and instead will tell the
programmer the syntax error. It also acts like a spell checker and
grammar checker.

The last to execute during the translation process is the


linker program. The linker is a third program that combines the
object file with the necessary parts of the run-time library. While
the object file has machine language instructions, the computer
cannot run the object file as a program. C++ also needs to use
another code library, called the run-time library, for common
operations. The result is the creation of an executable file with
a .exe extension.

Sample Program 2:

#include <stdio.h>
int main ()
{
printf(“Hello world!\n");
return 0;
}

Course Module: Computer Programming 456


Course
Packet
LM03-EAAC

02 0203

Memory and Data Types

Computer programs consist of instructions and data.


Course Packet 02

Data is the information that is the subject of the program.


Computer programs’ instructions and data have to be in the
computer’s memory for the program to work. Memory is used
to store and recall information. Information, also called data,
comes in different forms. The type of data, whether numeric, text
or something else is referred to as the data type. The data type
will affect not only the form in which the data is stored but also
the amount of memory required to store it.

Data Types

The ones and zeros that may be stored at a memory


address may represent text and a whole number. Data comes in
many forms and is generally either numeric or textual. Some
numeric data uses whole numbers, while others uses floating-
point numbers. There are different data types for each of the
many forms of data. The data type chosen will affect not only
the form in which the data is stored but also the amount of
memory required to store the data.

Whole Number Data Types

There are several different whole-number data types.


The listed sizes and range are typical but may vary depending
on the compiler and operating system. Use sizeof operator to
determine through code the size of different data types on the
compiler and operating system.

Table 49. Whole Number Data Types


Data Types Size (Bytes) Range
short 2 -32,768 to 32,767
unsigned short 2 0 to 65,535
int 4 -2,147,483,648 to 2,147,483,647
unsigned int 4 0 to 4,294,967,295
long 4 -2,147,483,648 to 2,147,483,647
unsigned long 4 0 to 4,294,967,295

Course Module: Computer Programming 457


Course
Packet
LM03-EAAC

02 0203

Unsigned vs. Signed Data Type

Unsigned means the number is always zero or positive,


Course Packet 02

never negative. While signed means the number may be


negative or positive (or zero). If the data type is not specified as
signed or unsigned, the data type is presumed to be signed.
Since an unsigned data type means its value is always 0 or
positive, never negative, the smallest value of an unsigned short
is, therefore, zero; an unsigned short cannot be negative. By
contrast, the smallest value of a short is -32767, since a signed
data type may be negative, positive, or zero.

Size

All C++ data types have a size. A byte is the smallest unit
of information that a computer can process, no data type may be
smaller than one byte. Regardless of the size, the number of
bytes is always a whole number. The number of bytes for a data
type is the result of a power of 2 since computers use a binary
number system. Size of data type matters in two related aspects:
the range of different values that the data type may represent and
the amount of memory required to store the data type.

Range

Range means the highest and lowest value that may be


represented by a given data type. The number of different values
that a data type can represent is 2𝑛 , n is the number of bits in the
data type. The highest number that an unsigned data type may
represent is 2𝑛−1 ; n is the number of bits in the data type, and the
minus 1 being used because we are starting at 0, not 1.

Signed data types involve an additional issue.


Determine if a decimal number is positive or negative by looking
to see if the number is preceded by a negative sign (-). However,
a bit can be only 1 or 0; there is no option for a negative sign in a
binary number. With a signed data type, different numbers must
be split evenly between those starting at zero and going up, and

Course Module: Computer Programming 458


Course
Packet
LM03-EAAC

02 0203

those starting at zero and going down. One of the bits is used to
store the sign, positive or negative.
Course Packet 02

Storage

A memory address can hold only 8 bits or a byte.

Figure 250: Storage in memory of 65365 in decimal as an unsigned short


data type

Figure 251: Storage in memory of 65365 in decimal as an unsigned int data


type

Floating-Point Data Types

Whole numbers work fine for certain information where


fractions don’t apply. Whole numbers also work fine for certain
information where fractions do apply but are not important.
There are floating-point data types that can be used when a value
to the right of the decimal point is important. The term floating
point comes from the fact that there is no fixed number of digits
before and after the decimal point; that is, the decimal point can
float. Floating-point numbers also are sometimes referred to as
real numbers.

Table 50. Floating-point Data Types


Data Types Size (Bytes) Range
float 4 +3.4E-38 to +3.4E38
double 8 +1.7E-308 to +1.7E308
long double 10 +3.4E-4932 to +3.4E4932

Since only ones and zeros can be stored in memory,


complex codes are required to store floating-point numbers.

Course Module: Computer Programming 459


Course
Packet
LM03-EAAC

02 0203

Even with complex codes, a computer can only approximately


represent many floating-point values.
Course Packet 02

Text Data Types

There are two text data types. The first is char, which
stands for character. It is usually is 1 byte, and can represent any
single character, including a letter, a digit, a punctuation mark,
or a space. The second text data type is a string. The string data
type may store several characters, including a sentence, or
paragraph, or page. The number of bytes required depends on
the number of characters involved.

Unlike char and the other data types, the string type is
not a data type built into C++. Instead, it is defined in the
standard library file string, which therefore must be included
with an include directive (#include<string.h>) to use the string
data type.

Boolean Data Types

The bool data type has only two possible values, true
and false, and its size usually is one byte. The term “bool” is a
shortening of Boolean, which is usually used in connection with
Boolean Algebra, named after the British mathematician, George
Boole. It could be regarded as a numeric data type in that zero is
seen as false, and one as true.

sizeof Operator

The sizeof operator is followed by parentheses, in which


you place a data type. It returns the size in bytes of that data
type.

Sample Program 3:

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

Course Module: Computer Programming 460


Course
Packet
LM03-EAAC

02 0203

cout<<“Size of short is “ <<sizeof(short) <<“\n”;


cout<<“Size of int is “ <<sizeof(int) <<“\n”;
cout<<“Size of long is “ <<sizeof(long) <<“\n”;
Course Packet 02

cout<<“Size of float is “ <<sizeof(float) <<“\n”;


cout<<“Size of double is “ <<sizeof(double) <<“\n”;
cout<<“Size of long double is “ <<sizeof(long double)
<<“\n”;
cout<<“Size of char is “ <<sizeof(char) <<“\n”;
cout<<“Size of bool is “ <<sizeof(bool) <<“\n”;
return 0;
}

Expressions

cout<<“Size of int is “ <<sizeof(int) <<“\n”;

The code sizeof(int) is called an expression. An


expression is a code statement that has a value, usually a value
that has to be evaluated when the program runs. The portion of
the statement within double quotes, “Size of int is “, is outputted
literary as “Size of int is 4.” There is no need for evaluation.
Instead, this is considered a literal string. The term string refers
to the data type, a series of characters, and the term literal refers
to the fact that the string is outputted literary, without
evaluation.

Outputting Expression

court<<“Size of int is sizeof(int) \n”;

The expression sizeof(int)is separated by the stream


insertion operator (<<) from the literal string “Size of int is ”.
sizeof(int), being encased inside the double quotes, would be
treated as a literal string, not an expression, and therefore would
not be evaluated, but instead displayed as is. Since “Size of int
is” is a literal string and sizeof(int) is an expression, they need to
be differentiated before being inserted into the output stream.
The differentiation is done by placing a stream insertion operator
between the literal string and the expression.

Course Module: Computer Programming 461


Course
Packet
LM03-EAAC

02 0203

Escape Sequence

The string “\n” following the expression sizeof(int) is


Course Packet 02

also a literal string, so it, too, is separated by a stream insertion


operator from the sizeof(int) expression. A special type of string
is called an escape sequence. C++ has many escape sequences.
The “\n” in a string is not displayed literally by cout even though
it is encased in double-quotes. The backslash signals cout that
this is an escape sequence.

Table 51. Escape Sequences in C Language


Escape
Name What it does
Sequence
\a Alarm Causes the computer to beep
\n Newline Causes the cursor to go to the next line
Causes the cursor to go to the next tab
\t Tab
stop
\\ Backslash Causes a backslash to be printed
Single
\’ Causes a single quote to be printed
Quote
Double
\” Causes a double quote to be printed
Quote

Variables

When there is a need to refer in code to a particular item


of information among perhaps thousands of items of
information, it is done by referring to the name of that
information item. Name information by creating a variable. A
variable not only gives a way of referring later to particular
information but also reserves the amount of memory necessary
to store that information.

Declaring Variables

The information a program uses while it is running first


needs to be stored in memory. There is a need to reserve memory
before storing information there. It is done by declaring a
variable. Declaring variables also gives a convenient way of
referring to the reserved memory when needed in the program.

Course Module: Computer Programming 462


Course
Packet
LM03-EAAC

02 0203

By declaring a variable, it refers to the reserved memory by the


variable’s name, which is easier to remember and identify with
the stored information than its hexadecimal address.
Course Packet 02

Syntax of Declaring Variables

It is a must to declare variables before using them. Name


is an alias by which you can refer in code to the area of reserved
memory. The variable declaration ends with a semicolon, it tells
the compiler that the statement has ended. Declare a variable
either within a function, such as main or above all functions, just
below any include directives.
Syntax:
datatype variablename;

A compiler error will be received if the variable is


referred to first before declaring it because the compiler reads the
code from top to bottom. When a variable is declared, then the
compiler recognizes further references to the variable name as
referring to the variable that was declared.

Declaring Multiple Variables of the Same Data Type

Several variables of the same data type could be declared


in a separate statement. Several variables of the same data type
could also be declared in one statement separated by commas.
Syntax:
datatype var1, var2, var3, ..., varn;
Example of Multiple Declarations:
int testScore;
int myWeight;
int myHeight;
Example of A Single Declaration:
int testScore, myWeight, myHeight;

The data types qualify all three variables since they


appear in the same statement as the data type. The variables
must all be of the same data type to be declared in the same
statement.

Course Module: Computer Programming 463


Course
Packet
LM03-EAAC

02 0203

Naming Variables

Variables have names that are used to identify the


Course Packet 02

variable so you can refer to it in code. It is also known as


identifiers.
Limitations on how a variable is named.
• The variable name cannot begin with any character other
than a letter of the alphabet (A-Z or a-z) or an underscore
(_). However, the second and following characters of the
variable name may be digits, letters, or underscores.
• The variable name cannot contain embedded spaces,
such as My Variable, or punctuation marks other than
the underscore character (_).
• The variable name cannot be the same as a word
reserved by C++.
• The variable name cannot have the same name as the
name of another variable declared in the same scope.

Standard reserved keywords


• asm, auto, bool, break, case, catch, char, class, const,
const_cast, continue, default, delete, do, double,
dynamic_cast, else, enum, explicit, export, extern, false,
float, for, friend, goto, if, inline, int, long, mutable,
namespace, new, operator, private, protected, public,
register, reinterpret_cast, return, short, signed, sizeof,
static, static_cast, struct, switch, template, this, throw,
true, try, typedef, typeid, typename, union, unsigned,
using, virtual, void, volatile, wchar_t, while
• Alternative representations for some operators: and,
and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor,
xor_e
• the compiler may also include some additional specific
reserved keywords

It is a good idea to give meaningful variable names. Use


a variable name that is descriptive of the purpose of the variable.

Course Module: Computer Programming 464


Course
Packet
LM03-EAAC

02 0203

Scope of A Variable

A variable can be either of global or local scope. A global


Course Packet 02

variable is a variable declared in the main body of the source


code, outside all functions. On the other hand, the local variable
is one declared within the body of a function or a block.

Figure 252: Variable Scope Examples

Naming Conventions

The naming convention is simply a consistent method of


naming variables. Another naming convention is to name a
variable with a prefix, usually all lowercase and consisting of
three letters, that indicate its data type, followed by a word with
its first letter capitalized, that suggests its purpose.
Example:
intScore
strName
blnResident

The different naming conventions that could be used are


Hungarian Notation and Camel Case Notation. The first naming
convention came to be known as “Hungarian Notation” because
the prefixes make the variable names look a bit as though they’re
written in some non-English language and because it is
originally from Hungary. The Hungarian naming convention is
quite useful it’s one technique among many that helps
programmers produce better code faster. The name of the
variable is its type and intended use.

Course Module: Computer Programming 465


Course
Packet
LM03-EAAC

02 0203

Example:
iNoofStudents = int – data type; No of Students
fAreaofCircle = float – data type; Area of Circle
Course Packet 02

The second naming convention is the Camel Case


Notation. It is the practice of writing compound words or
phrases in which the words are joined without spaces and are
capitalized within the compound word thus looking like a hump
of a camel.
Example:
employeeName
studentNumber

The Address Operator

Declaring a variable reserves memory. Use the address


operator (&) to learn the address of this reserved memory.
Syntax:
&variablename

Sample Program 4:

#include <iostream.h>
int main ()
{
int testScore;
cout<<&testScore;
return 0;
}

The operating system, not the programmer, chooses the


address at which to store a variable. The particular address
chosen by the operating system depends on the data type of the
variable, how much memory already has been reserved, and
other factors.

Course Module: Computer Programming 466


Course
Packet
LM03-EAAC

02 0203

Using the Address and sizeof Operators with Variables

Use the sizeof operator to learn the size of different data


Course Packet 02

types. Also, use the sizeof operator to determine the size of


different variables. The parentheses following the sizeof
operator refer to a data type or variable name.

Sample Program 5:

#include <iostream.h>
int main ()
{
short testScore;
float myGPA;
cout<<“The address of testScore is “ <<&testScore <<
“\n”;
cout<<“The size of testScore is “ <<sizeof(testScore) <<
“\n”;
cout<<“The address of myGPA is “ <<&myGPA << “\n”;
cout<<“The size of myGPA is “ <<sizeof(myGPA) <<
“\n”;
return 0;
}

The operating system often attempts to place declared


variables near each other. However, this is not always possible,
depending on factors such as the size of the variables and
memory already reserved. There is no guarantee that two
variables will even be near each other in memory.

Assigning Values to Variables

The purpose of a variable is to store information. After


creating a variable, the next logical step is to specify the
information that the variable will store. This is called assigning
a value to a variable. A variable can be assigned a value supplied
by the programmer in code. A variable also can be assigned a
value by the user, usually via the keyboard, when the program
is running.

Course Module: Computer Programming 467


Course
Packet
LM03-EAAC

02 0203

Assignment Operator

Use the assignment operator to assign a value to a


Course Packet 02

variable. The assignment operator looks like the equal sign.


However, in C++ the = sign is not used to test for equality; it is
used for assignment. In C++ the equal sign is ==, also called the
equality operator. The variable must be declared either before,
or at the same time, it is assigned a value, not afterward.
Syntax:
variablename = value;
Example:
int testScore;
testScore = 95;

Initialization is when a variable is assigned a value as


part of the same statement that declares that variable.
Syntax:
datatype variablename = value;
Example:
int testScore=95;

A variable cannot be declared after it is assigned a value.


Example:
testScore = 95;
int testScore;
The value assigned to a variable need not be a literal value.
Example:
int a, b;
a = 44;
b = a;
A value can be assigned to several variables at once.
Example:
int a, b, c;
a = b = c = 0;
Also, another value can be assigned again to a variable after it
has already been assigned a value because variable means likely
to change or vary.

Course Module: Computer Programming 468


Course
Packet
LM03-EAAC

02 0203

Sample Program 6:

#include <iostream.h>
Course Packet 02

int main ()
{
int testScore;
testScore = 95;
cout<<“Your test score is “ <<testScore << “\n”;
testScore = 75;
cout<<“Your test score now is “ <<testScore << “\n”;
return 0;
}

Assigning a “Compatible” Data Type

The value assigned to a variable must be compatible


with the data type of the variable that is the target of the
assignment statement.
Example:
int testScore;
testScore = “Jeff”;
The value being assigned need not necessarily be the same data
type as the variable to which the value is being assigned.

Sample Program 7:

#include <iostream.h>
int main ()
{
int testScore;
testScore = 77.83;
cout<<“The test score is “<<testScore <<“\n”;
return 0;
}

Course Module: Computer Programming 469


Course
Packet
LM03-EAAC

02 0203

Overflow and Underflow

Overflow occurs when a variable is assigned a value too


Course Packet 02

large for its range. The value overflows and wraps around to the
data type’s lowest possible value.

Sample Program 8:

#include <iostream.h>
int main ()
{
short testScore;
testScore = 32768;
cout<<“The test score is “<<testScore <<“\n”;
return 0;
}

Figure 253: Overflow

The converse of overflow is an underflow. Underflow


occurs when a variable is assigned a value too small for its range.
The value underflows and wraps around to the data type’s
highest possible value.

Sample Program 9:

#include <iostream.h>
int main ()
{
short testScore;
testScore = -32769;
cout<<“The test score is “<<testScore <<“\n”;
return 0;

Course Module: Computer Programming 470


Course
Packet
LM03-EAAC

02 0203

}
Course Packet 02

Figure 254: Underflow

Using the cin Operator

Use the cin object to obtain information from standard


input, which usually is the keyboard. It is defined in the
standard library file <iostream.h>. The cin object is followed by
>>, which is the stream extraction operator. It obtains the input,
usually from the keyboard, and assigns that input to the variable
to its right. A cin statement usually is preceded by a cout
statement telling the user what to do. This is called a prompt.
Syntax:
cin>>variablename;

Sample Program 10:

#include <iostream.h>
int main ()
{
int testScore;
cin>> testScore;
cout<<“Your testScore is “<<testScore <<“\n”;
return 0;
}

Sample Program 11:

#include <iostream.h>
int main ()
{
int testScore;
cout<<“Enter your test score: “;

Course Module: Computer Programming 471


Course
Packet
LM03-EAAC

02 0203

cin>> testScore;
cout<<“Your testScore is “<<testScore <<“\n”;
return 0;
Course Packet 02

Assigning a “Compatible” Data Type

The value being assigned by the cin operator need not


necessarily be the same data type as that of the variable to which
the value is being assigned. The value being assigned by the cin
operator must be compatible with the data type of the variable to
which the value is being assigned. There would be no compile
error since at the time of compilation there was no attempt to
assign an incompatible value. The error will be known only at
run time. The data types in the cin statement may be different.
What is important is that the order of the input matches the order
of the data types of the variables in the cin statement.

Inputting Values for Multiple Variables

Sample Program 12:

#include <iostream.h>
int main()
{
int myWeight, myHeight;
string myName;
cout<<“Enter your name: ”;
cin>>myName;
cout<<“Enter your weight in pounds: ”;
cin>>myWeight;
cout<<“Enter your height in inches: ”;
cin>>myHeight;
cout<<“Your name score is ” <<myName <<“\n”;
cout<<“Your weight in pounds is ” <<myWeight <<“\n”;
cout<<“Your height in inches is ” <<myHeight <<“\n”;
return 0;
}

Course Module: Computer Programming 472


Course
Packet
LM03-EAAC

02 0203

Instead of having separate prompts and cin statements


for each variable, have one cin statement assign values to all
three variables. When using one cin statement to assign values
Course Packet 02

to multiple variables, the user separates each input by one or


more spaces. The space tells the cin object that the user has
finished assigning a value to one variable and the next input
should be assigned to the next variable in the cin statement. As
before, the user finishes input by choosing the ENTER key.
Syntax:
cin >>firstvariable>>secondvariable>>thirdvariable;

Sample Program 13:

#include <iostream.h>
int main()
{
int myWeight, myHeight;
string myName;
cout<<“Enter your name, weight in pounds and height
in inches\n: ”;
cin>>myName >>myWeight >>myHeight;
cout<<“Your name score is ” <<myName <<“\n”;
cout<<“Your weight in pounds is ” <<myWeight <<“\n”;
cout<<“Your height in inches is ” <<myHeight <<“\n”;
return 0;
}

Inputting Multiple Words into a String

The cin operator will only take the first word of a string.
cin object interprets the space between texts as indicating that the
user has finished inputting the value of the variable. The
solutions for this involve using either the get or getline method
of the cin object.

Sample Program 14:

#include <iostream.h>
#include <string.h>

Course Module: Computer Programming 473


Course
Packet
LM03-EAAC

02 0203

int main ()
{
string name;
Course Packet 02

cout<< “Enter your name: “;


cin>> name;
cout<< “Your name is “ <<name;
return 0;
}

Arithmetic Operators

Many computer programs need to perform calculations.


Computers, in addition to being able to store vast amounts of
data, also can calculate far more quickly and accurately than a
human can.

An operator is a symbol that represents a specific action.


Operators used for arithmetic are called arithmetic operators.

Table 52. Arithmetic Operators in C Language


Operator Purpose Example Result
+ Addition 5+2 7
– Subtraction 5–2 3
* Multiplication 5*2 10
/ Division (Quotient) 5/2 2
% Division (Remainder) 5%2 1

% operator, also called the modulus operator, returns the


remainder in the division. Arithmetic operators are binary
operators because they operate on two operands, binary being a
reference to 2, and operand referring to each of the two values
that are in the arithmetic expression. Note that not all operators
are binary. The negative sign or negation is a unary operator
because it operates on only one operand. There are also ternary
operators, which operates on 3 operands.

Arithmetic operators work with negative as well as


positive numbers, and, except for the modulus operator,

Course Module: Computer Programming 474


Course
Packet
LM03-EAAC

02 0203

floating-point numbers as well as whole numbers. The addition


operator also works with strings as well as with numbers.
Course Packet 02

The Addition Operator

Sample Program 15:

#include <iostream.h>
int main ()
{
int total, added;
cout<<“Enter number of pre-registered students: “;
cin>>total;
cout<<“Enter number of students adding the course: “;
cin>>added;
total = total + added;
cout<<“Total number of students: “ <<total;
return 0;
}

Combined Assignment and Arithmetic Operator

total = total + added;

In Mathematics, a variable cannot equal itself plus


another number. In C++ programming, the = operator is not used
for equality but instead for assignment. Another way to express:
total += added;
The compact form of combining arithmetic and assignment
operators is not limited to the addition operator. It can also be
used with the other arithmetic operators.

Table 53. Compact Form for Arithmetic Operators


Statement Combining Operators
a = a + 2; a += 2;
a = a – 2; a –= 2;
a = a * 2; a *= 2;
a = a / 2; a /= 2;
a = a % 2; a %= 2;

Course Module: Computer Programming 475


Course
Packet
LM03-EAAC

02 0203

The arithmetic operation has precedence over the


assignment operation. The addition is performed before the
assignment. Precedence also arises when more than one
Course Packet 02

arithmetic operator is used in a statement.

Overflow and underflow apply to the results of addition.

Adding Strings

Although addition does involve numeric operands, the


addition operator also can be used with string operands. Adding
two strings has the effect of appending the second-string
operand to the first-string operand. Appending means adding
the contents of the second string to the end of the first string.
While numbers and numbers or strings and strings can be added,
attempting to add a number and a string will cause a compile
error.

Sample Program 16:

#include <iostream.h>
#include <string.h>
int main ()
{
string firstName = “Jeff”;
string lastName = “Kent”;
cout <<“Your name is “ <<firstName + lastName;
return 0;
}

The Subtraction Operator

Sample Program 17:

#include <iostream.h>
int main ()
{
int total, added, dropped;
cout <<“Enter number of pre-registered students: “;

Course Module: Computer Programming 476


Course
Packet
LM03-EAAC

02 0203

cin >> total;


cout <<“Enter number of students adding the course: “;
cin >> added;
Course Packet 02

total = total + added;


cout <<“”How many students dropped? “;
cin >> dropped;
total -= dropped;
cout <<“Total number of students: “ << total << endl;
return 0;
}

The effect of overflow and underflow is the same with


the subtraction operator as with the addition operator. Unlike
the addition operator, the subtraction operator will not work
with string operands.

The Multiplication Operator

Sample Program 18:

#include <iostream.h>
int main ()
{
int total, added, dropped;
cout <<“Enter number of pre-registered students: “;
cin >> total;
cout <<“Enter number of students adding the course: “;
cin >> added;
total = total + added;
cout <<“”How many students dropped? “;
cin >> dropped;
total -= dropped;
cout <<“Total number of students: “ <<total <<endl;
cout <<“Total tuition owed: $” <<(total + dropped) * 72
<<endl;
return 0;
}

Course Module: Computer Programming 477


Course
Packet
LM03-EAAC

02 0203

The effect of overflow and underflow is the same with


the multiplication operator as with the addition and subtraction
operators. Unlike the addition operator, but like the subtraction
Course Packet 02

operator, the multiplication operator will not work with string


operands.

Precedence Between Arithmetic Operators

The order in which the two arithmetic operations are


performed makes a difference. C++ has a rule, called precedence,
for determining which operation is performed first.

Table 54. Arithmetic Operators Precedence


Precedence Arithmetic Operators
Highest (–) unary negation
Middle */%
Lowest +–

C++ also has rules called associativity for determining


which operation is performed first when two operators have
equal precedence.

Table 55. Arithmetic Operators Associativity


Precedence Arithmetic Operators
(–) unary negation Right to Left
*/% Left to Right
+– Left to Right

Override the default precedence with parentheses.


Expressions in parentheses are done first.

The Division Operators

The division has two operators. The / operator gives the


quotient while the % (or modulus operator) gives the remainder.

Course Module: Computer Programming 478


Course
Packet
LM03-EAAC

02 0203

The Division Operator

Division operator returns the quotient. The value of the


Course Packet 02

quotient depends on whether at least one of the operands is a


floating-point data type. In C++, when both operands are an
integer or other whole number data type, then the result is an
integer as well, and the remainder is not part of the quotient.

Sample Program 19:

#include <iostream.h>
int main ()
{
int firstOp = 10, secondOp = 4;
float result = firstOp / secondOp;
cout<< firstOp << “ / “ <<secondOp << “ = “ << result;
return 0;
}

When at least one of the operands is a floating-point data


type, then the result is a floating-point as well.

Sample Program 20:

#include <iostream.h>
int main ()
{
float firstOp = 10, result;
int secondOp = 4;
result = firstOp / secondOp;
cout<< firstOp << “ / “ <<secondOp << “ = “ << result;
return 0;
}

If the result of the division of two integer variables needs


to be float, then cast one of the variables to float. A cast does not
change the data type of the variable, just the data type of the
value of the variables during the completion of the operation.
Cast the variable by putting the desired data type in front of it in

Course Module: Computer Programming 479


Course
Packet
LM03-EAAC

02 0203

an expression, and placing either the desired data type or the


variable in parentheses.
Course Packet 02

Sample Program 21:

#include <iostream.h>
int main()
{
int firstOp = 10, secondOp = 4;
float result = (float)firstOp / secondOp;
cout<< firstOp << “ / “ <<secondOp << “ = “ << result;
return 0;
}

Sample Program 22:

#include <iostream.h>
int main()
{
int total, added, dropped, tuition;
cout <<“Enter number of pre-registered students: “;
cin >> total;
cout <<“Enter number of students adding the course: “;
cin >> added;
total = total + added;
cout <<“”How many students dropped? “;
cin >> dropped;
total -= dropped;
cout <<“Total number of students: “ <<total <<endl;
tuition =(total + dropped) * 72;
cout <<“Total tuition owed: $ ” <<tuition <<endl;
cout <<“Average tuition per enrolled students:
$” <<(float) tuition/total <<endl;
return 0;
}

Course Module: Computer Programming 480


Course
Packet
LM03-EAAC

02 0203

The Modulus Operator

Modulus operator also involves division but returns


Course Packet 02

only the remainder. Modulus operator works only with whole


number operands. The result of an attempt to use it with a
floating-point operand is undefined. The result often is a
compile error. Whether using the / or the % operator, it cannot
divide by zero. The result is an error.

Exponent

C++, unlike some programming languages, does not


have an exponent operator. Instead, it has a built-in function
named pow, which is defined in the standard library file math.
pow is shorthand for power since with exponents one number is
raised to the power of another. pow function has two arguments.
The first argument is the number that is being raised to a certain
power. The second argument is the power the first argument is
being raised to.
Example:
pow (4,2)

pow function returns a double data type. Floating-point


numbers also can be raised to a power, resulting in another
floating-point number. Whole numbers can be raised to a
negative power, which also may result in a floating-point
number.

Sample Program 23:

#include <iostream.h>
#include <math.h>
int main()
{
double radius, area;
cout <<“Enter radius of circle: “;
cin >>radius;
area = 3.14159 * pow (radius, 2);
cout <<“The area is “ <<area << endl;

Course Module: Computer Programming 481


Course
Packet
LM03-EAAC

02 0203

return 0;
}
Course Packet 02

Change Machine Program

Create the flowchart and pseudocode of a program that


will ask the user to input the number of 5-centavos. The code
then will determine and display the equivalent number of
twenty pesos, 10 pesos, 5 pesos, 1 peso, 25-centavos, 10-centavos
and 5-centavos from the user input. (P25 = 400pcs of 5¢, P10 =
200pcs of 5¢, P5 = 100pcs of 5¢, P1 = 20pcs of 5¢, 25¢ = 5pcs of 5¢,
10¢ = 2pcs of 5¢ and 5¢ = 1pc of 5¢)

Course Module: Computer Programming 482


Course
Packet
LM03-EAAC

02 0203

Collaborative Learning Exercise 8


C Programming
Collaborative Learning Exercise 8

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with cover page in our Google Classroom. Keep
your work clean and avoid erasures. Use of pencil is prohibited. Use only a blue ballpoint pen.

Create the flowchart of a program that will ask the user to input the value of the temperature
in Celsius, Fahrenheit, Kelvin, and Rankine. The code then will determine the equivalent
temperature in the other units of temperature. Display the input and equivalent temperatures.
Code the resulting flowchart. (C to K, F, R; F to C, K, R; K to C, F, R; and R to C, F, K). (45 points)

Course Module: Computer Programming 483


Course
Packet
LM03-EAAC

02 0203

Laboratory Report 7
C Programming
Laboratory Report 7

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with cover page in our Google Classroom. Keep
your work clean and avoid erasures. Use of pencil is prohibited. Use only a blue ballpoint pen.

Create the flowchart of a program that will ask the user to input the number of pennies. The
code then will determine the equivalent number of dollars, quarters, dimes, nickels, and
pennies from the user input. Display the equivalent number of dollars, quarters, dimes, nickels,
and pennies. Code the resulting flowchart. (Dollar = 100 pennies, Quarters = 25 pennies, Dimes
= 10 pennies, Nickels = 5 pennies and Penny = 1 penny). (25 points)

Course Module: Computer Programming 484


Course
Packet
LM03-EAAC

02 0203

Practical Exam 7
C Programming
Practical Exam 7

(Topics Covered: All the topics in Course Packet 02 of Learning Module 03)

Remember:
The Practical Exam will be administered face-to-face. You are given an hour to answer this
practical exam. This is an individual assessment, therefore, individual submission of answer to
is required. Cheating in any form is highly discouraged.

Course Module: Computer Programming 485


Course
Packet
LM03-EAAC

02 0203

References
C Tutorial. (n.d.). Retrieved from W3schools.in: https://www.w3schools.in/c-tutorial/intro/
References

C++ Language. (2000). Retrieved June 27, 2016, from cplusplus.com:


http://www.cplusplus.com/doc/tutorial/

Doyle, B. (2014). C# Programming From Problem Analysis to Program Design Fourth Edition. New
Tech Park, Singapore: Cengage Learning Asia Pte Ltd.

Kent, J. (2005). C++ Demystified. USA: Mc Graw Hill Osborne.

Savitch, W. (1996). Problem Solving with C++ The Object of Programming. California, USA:
Addison-Wesley Publishing Company, Inc.

Schildt, H. (1992). Turbo C/C++: The Complete Reference, Second Edition. California, USA:
Osborne Mc-Graw Hill.

Sellappan, P. (2001). C++ Through Examples. Selangor Darul Ehsan, Malaysia: Federal
Publication Sdn. Berhad.

tutorialspoint. (2020). (Tutorials Point (I) Pvt. Ltd.) Retrieved July 3, 2020, from
https://www.tutorialspoint.com/cprogramming/index.htm

Course Module: Computer Programming 486


Course
Packet
LM03-EAAC

02 0203

Learner’s Feedback Form


Learner’s Feedback Form

Name of Student: _____________________________________________________________


Program : _____________________________________________________________
Year Level : ________ Section : _____ Sex at Birth: ___________
Faculty : _____________________________________________________________
Schedule : _____________________________________________________________

Course Packet : Code : _________ Title : __________________________________

How do you feel about the topic or concept presented?


 I completely get it.  I’m struggling.
 I’ve almost got it.  I’m lost.

In what particular portion of this course packet, do you feel that you are struggling or lost?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Did you raise your concern to your instructor?  Yes  No

If Yes, what did he/she do to help you?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

If No, state your reason?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

To further improve this course packet, what part do you think should be enhanced?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

How do you want it to be enhanced?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Course Module: Computer Programming 487


Course
Packet
LM03-EAAC

02
03 0203

Learning Module 03

Computer
Programming Using C
Language
Course Packet 03

Selection Structures

Knowledge Area Code : EAAC


Course Code : EAAC0203
Learning Module Code : LM03-EAAC0203
Course Packet Code : LM03-EAAC0203-03

Course Module: Computer Programming 488


Course
Packet
LM03-EAAC

03 0203

Course Packet 03
Course Packet 03

Selection Structures
Introduction

This course packet introduces the students to the different selection structures and
different relational operators to be used in a C program. The selection structure’s function and
syntax will be discussed with the students to familiarize themselves in its usage and be able to
manipulate the flow of the process in a program. Different relational operators will also be
discussed and demonstrated to give students hands-on experience in data and process
manipulation in a C program.

Objectives

At the end of the course packet, the students will be able to:
• Make use of the different selection structures to manipulate the process flow of a C
program.
• Create gender-responsive source code of different programming problems with the help
of a flowchart and pseudocode.

Learning Management System

BSEE 1C Google Classroom Link: https://classroom.google.com/c/NjYzNDQ1NDE2NTAx?cjc=e55hvj2


BSEE 1D Google Classroom Link: https://classroom.google.com/c/NjYzNDQzMDU2MTI0?cjc=fbfpl6c

Duration

• Topic 03: Selection Structures = 12 hours


(9 hours self-directed learning and 3 hours assessment)

Delivery Mode

Course Packet 3, Selection Structures, will be delivered via onsite learning (face-to-face), online
learning (synchronous) and offsite learning (asynchronous).

Assessment with Rubrics

The following criteria and the corresponding percentage shall be used to assess the
collaborative learning exercises and laboratory reports as an assessment tool or task.

Criteria Description %
Able to execute calculations correctly by hand and
Calculation apply appropriate mathematical 50%
equations/formulas.
Solution All the answers are correct and properly labeled. 20%

Course Module: Computer Programming 489


Course
Packet
LM03-EAAC

03 0203

Written work is presented neatly and


Neatness 10%
professionally.
Document Submitted work conforms to the prescribed
Course Packet 03

10%
Formatting format.
Work is submitted on or before the specified date
Timeliness 10%
and time.
TOTAL 100%

Requirement with Rubrics

Each student is required to accomplish the collaborative learning exercise and laboratory report
found after reading the course packet. The accomplished collaborative learning exercise and
laboratory report should be posted or submitted at the Google Classroom stream page of the
class on the scheduled date to be given by the faculty in charge.

Readings

1. C++ Demystified by Jeff Kent


2. C++ Through Examples by Dr. Palaniappan Sellappan
3. C# Programming from Problem Analysis to Program Design by Barbara Doyle
4. Turbo C/C++ The Complete Reference Second Edition by Herbert Schildt
5. https://www.tutorialspoint.com/cprogramming/index.htm
6. https://www.w3schools.in/c-tutorial/intro/

Course Module: Computer Programming 490


Course
Packet
LM03-EAAC

03 0203

Introduction
Key Points:

Control Structures can be considered as the building


Course Packet 03

• C programming
blocks of computer programs. They are commands that enable a language assumes any
non-zero and non-null
program to make decisions, following one path or another. A values as true, and if it
program is usually not limited to a linear sequence of is either zero or null,
then it is assumed as
instructions since during its process it may divide, repeat code false value.
or avoid sections. Control Structures are the blocks that analyze • Selection structures
require that the
variables and choose directions in which to go based on given
programmer specifies
parameters. one or more conditions
to be evaluated by the
program, along with
Lesson Proper statements to be
executed if the
condition is determined
Making Decision to be true, and
optionally, other
statements to be
Computer programs present their users with choices. executed if the
The flow of each program has followed a relatively straight line, condition is determined
to be false.
taking a predetermined path from beginning to end. However,
as programs become more sophisticated, they often branch in Definition of Terms:
two or more directions based on a choice a user makes. Function call. A control
structure that is used to
invite or call a piece of
The program determines the action it takes by code or statement. In this
comparing the user’s choice with the various alternatives. case control jumps from
main program to that
Comparison is made using a relational operator. The relational
piece of code and then
operators are used to test for equality, inequality, whether one returns back to main
program.
value is greater (or less) than another, and other comparisons.
Repetition Structures. A
control structure where
The code then needs to be structured so different code the statements are
executed more than one
executes depending on which choice was made. It could be done time. It is also known as
using the if statement or the switch case statement. Flowcharting iteration or loop.
Selection Structures. A
enables the programmer to visually depict the flow of a program. control structure that
It becomes increasingly helpful in transitioning from relatively selects a statement to
execute on the basis of
simple programs that flow in a straight line to more complex condition. Statement is
programs that branch in different directions. executed when the
condition is true and
ignored when it is false.
Relational Operators Sequential Structures. A
control structure that is
executed in a specified
Humans make comparisons all the time, and so do order. No statement is
skipped and executed
programs. A program may need to determine whether one value more than once.

Course Module: Computer Programming 491


Course
Packet
LM03-EAAC

03 0203

is equal to, greater than, or less than another value.

Table 56. Relational Operators


Course Packet 03

Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

Relational Expressions

Like the arithmetic operators, the relational operators


are binary – that is, they compare two operands. A statement
with two operands and a relational operator between them is
called a relational expression. The result of a relational
expression is a Boolean value, depicted as either true or false.
Operands can also be variables.

Sample Program 24:

#include <iostream.h>
int main ()
{
int a = 4, b = 5;
cout<< a <<“ > ” << b <<“ is “ << (a > b) << endl;
cout<< a <<“ >= ” << b <<“ is “ << (a >= b) << endl;
cout<< a <<“ == ” << b <<“ is “ << (a == b) << endl;
cout<< a <<“ <= ” << b <<“ is “ << (a <= b) << endl;
cout<< a <<“ < ” << b <<“ is “ << (a < b) << endl;
return 0;
}

0 is the integer value of Boolean false, while 1 is the usual


integer value of Boolean true. While the usual integer value of
logical true is 1, any non-zero number may be logically true.
Therefore, in a Boolean comparison, do not compare a value to 1,
compare it to true. The data types of the two operands need not

Course Module: Computer Programming 492


Course
Packet
LM03-EAAC

03 0203

be the same. However, the data types of the two operands need
to be compatible.
Course Packet 03

Precedence

Relational operators have higher precedence than


assignment operators and lower precedence than arithmetic
operators. Operators in the same row have equal precedence.
The associativity of relational operators of equal precedence is
from left to right.

Table 57. Relational Operators Precedence


Precedence Operator
Highest >, <, >=, <=
Lowest = =, !=

The if Statement

The if statement is used to execute code only when the


value of a relational expression is true.
Syntax:
if (relational expression)
conditional statement;

The first line consists of the if keyword followed by an


expression, such as a relational expression, that evaluates to a
Boolean value, true or false. The relational expression must be
in parentheses, and should not be terminated with a semicolon.

The next line is called a conditional statement. A


statement is an instruction to the computer, directing it to
perform a specific action. The statement is conditional because
it executes only if the value of the relational expression is true. If
the value of the relational expression is false, then the conditional
statement is not executed.

Sample Program 25:

#include <iostream.h>

Course Module: Computer Programming 493


Course
Packet
LM03-EAAC

03 0203

int main ()
{
int num;
Course Packet 03

cout << “Enter a whole number: “;


cin >> num;
if (num % 2 == 0)
cout << “The number is even” << endl;
return 0;
}

Indenting

It is good practice to indent the conditional statement.


The compiler doesn’t care whether you indent or not,
indentation makes it easier for the programmer to see that the
statement is conditional.
Example:
if (num % 2 == 0)
cout << “The number is even” << endl;

Common Mistakes

Some of these mistakes may result in compiler errors


and therefore are easy to spot. Other mistakes are harder to pick
out since they do not cause an error, either at compile-time or
run-time, but instead give rise to illogical results.

Don’t Put a Semicolon after the Relational Expression!

The first common mistake is to place a semicolon after


the relational expression.
Example:
if (num % 2 == 0);
cout << “The number is even” << endl;
The compiler generally ignores blank spaces.
Example:
if (num % 2 == 0)
;
cout << “The number is even” << endl;

Course Module: Computer Programming 494


Course
Packet
LM03-EAAC

03 0203

No compiler error will result. The compiler error will assume


from the semicolon that it is an empty statement. An empty
statement does nothing. One consequence will be that the empty
Course Packet 03

statement will execute if the relational expression is true. An


additional consequence is an illogical result. The cout statement
will execute whether or not the relational expression is true
because it is no longer a part of the if statement. Unless you use
curly braces. Only the first statement following the if keyword
and relational expression are conditional. The first conditional
statement is the empty statement, because of the semicolon
following the if expression.

Curly Braces Needed for Multiple Conditional Statements

Unless curly braces are used, only the first statement


following the if keyword and relational expression are
conditional.
Example:
if (num % 2 == 0)
cout << “The number is even” << endl;
cout << “And the number is not odd” << endl;
If more than one statement is to be part of the overall if statement,
encase these statements in curly braces.
Example:
if (num % 2 == 0)
{
cout << “The number is even” << endl;
cout << “And the number is not odd” << endl;
}

Don’t Mistakenly Use the Assignment Operator!

The third most common syntax error is to use the


assignment operator instead of the relational equality operator
because the assignment operator looks like an equal sign.
Example:
if (num % 2 = 0)
cout << “The number is even” << endl;
The result is that the if expression will not evaluate as the result

Course Module: Computer Programming 495


Course
Packet
LM03-EAAC

03 0203

of a comparison. Instead, it will evaluate the expression within


the parentheses as the result of the assignment, with a non-zero
value being regarded as true, a zero value is regarded as false.
Course Packet 03

Some compilers will treat this mistake as a compiler error.

The if … else Statement

Syntax:
if (relational expression)
conditional statement;
else
conditional statement;

Sample Program 26:

#include <iostream.h>
int main ()
{
int num;
cout << “Enter a whole number: ”;
cin >> num;
if (num % 2 == 0)
cout << “The number is even” << endl;
else
cout << “The number is odd” << endl;
return 0;
}

Common Mistakes

No else Without an if

A program can have an if expression without an else


part. However, the program cannot have an else part without an
if part. The else part must be part of an overall if statement. The
else part works as “none of the above”; without an if part there
is no “above”.

Placing a semicolon after the Boolean expression

Course Module: Computer Programming 496


Course
Packet
LM03-EAAC

03 0203

following the if keyword will result in a compiler error. Since


curly braces are not used, the if statement ends after the empty
statement created by the incorrectly placed semicolon.
Course Packet 03

Example:
if (num % 2 == 0);
cout << “The number is even” << endl;
else (num % 2 == 1)
cout << “The number is odd” << endl;

Don’t Put a Relational Expression after the else Keyword!

Another common mistake is to place a relational


expression in parentheses after the else keyword. It will not
cause a compiler or run-time error, but it will often cause an
illogical result.
Example:
if (num % 2 == 0)
cout << “The number is even” << endl;
else (num % 2 == 1)
cout << “The number is odd” << endl;
The program will not compile, and the cout statement following
the else expression will be highlighted with an error description
such as “missing ‘;’ before identifier ‘cout’.”

Don’t Put a Semicolon after the Else!

Another common mistake is to place a semicolon after


the else expression. It will not cause a compiler or run-time error
but often will cause an illogical result.
Example:
if (num % 2 == 0)
cout << “The number is even” << endl;
else;
cout << “The number is odd” << endl;

Curly Braces Are Needed for Multiple Conditional Statements

If the programmer wants more than one conditional


statement to belong to the else part, then the programmer must

Course Module: Computer Programming 497


Course
Packet
LM03-EAAC

03 0203

encase the statements in curly braces.


Example:
if (num % 2 == 0)
Course Packet 03

cout << “The number is even” << endl;


else
cout << “The number is odd” << endl;
cout << “This also belongs to the else part”;
To solve:
if (num % 2 == 0)
cout << “The number is even” << endl;
else
{
cout << “The number is odd” << endl;
cout << “This also belongs to the else part”;
}

Conditional Operator

The conditional operator requires three operands, the


relational expression and the two conditional statements.
Therefore, it is considered a ternary operator.
Syntax:
[relational expression]?[statement if true]:[statement if
false]

Sample Program 27:

#include <iostream.h>
int main ()
{
int num;
cout << “Enter a whole number: ”;
cin >> num;
cout << “The number is “<< (num % 2 == 0? “even”:
“odd”) << endl;
return 0;
}

Course Module: Computer Programming 498


Course
Packet
LM03-EAAC

03 0203

The if … else if … else Statement

The if … else statement involved only two alternatives.


Course Packet 03

These alternatives are mutually exclusive; only one could be


chosen, not both. There are other scenarios where there are more
than two, mutually exclusive alternatives. Since only one if
expression and only one else expression in an if statement and if
… else statement, the programmer needs another expression for
the third and additional alternatives.

Use the if … else if … else statement when there are three


or more mutually exclusive alternatives. The if … else if … else
statement has an if part and an else part, like an if … else
statement. However, it also has one or more else if parts. While
the if part is required, the else part is not. Without it, the
statement would be named an if/ else if statement.

The else if part works similarly to an if expression. The


else if keywords are followed by a relational expression. If the
expression is true, then the conditional statement or statements
belonging to the else if part execute. Otherwise, they don’t.
While an if statement may include only one if part and one else
part, it may include multiple else if parts.
Syntax:
if (relational expression)
conditional statement;
else if (relational expression)
conditional statement;
else if (relational expression)
conditional statement;

else
conditional statement;

Sample Program 28:

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

Course Module: Computer Programming 499


Course
Packet
LM03-EAAC

03 0203

int testScore;
cout <<“Enter your test score: ”;
cin >> testScore;
Course Packet 03

if (testScore >= 90)


cout << “Your grade is an A” <<endl;
else if (testScore >= 80)
cout << “Your grade is a B” <<endl;
else if (testScore >= 70)
cout << “Your grade is a C” <<endl;
else if (testScore >= 60)
cout << “Your grade is a D” <<endl;
else
cout << “Your grade is an F” <<endl;
return 0;
}

Common Syntax Errors

The common syntax errors for the if part applies to the


else if part also. Don’t put a semicolon after the relational
expression, and multiple conditional statements must be
enclosed in curly braces. An else part must have a preceding if
part, have an else if part also must have a preceding if part.

However, a program may have an if part and one or


more else if parts without an else part. The downside in omitting
the else part is that the program will not have code to cover the
“none of the above” scenario in which none of the relational
expressions belong to the if part and else if parts are true.

The switch Statement

The switch statement is similar to an if … else if … else


statement. It evaluates the value of an integer expression and
then compares that value to two or more other values to
determine which code to execute.
Syntax:
switch(var)
{

Course Module: Computer Programming 500


Course
Packet
LM03-EAAC

03 0203

case value1:
statement/s;
break;
Course Packet 03

case value2:
statement/s;
break;

default:
statement/s;
}

Sample Program 29:

#include <iostream.h>
int main ()
{
char grade;
cout << “Enter your grade: ”;
cin >> grade;
switch (grade)
{
case ‘A’:
cout<< “Your average must be between
90 - 100” <<endl;
break;
case ‘B’:
cout << “Your average must be between
80 - 89” <<endl;
break;
case ‘C’:
cout << “Your average must be between
70 - 79” <<endl;
break;
case ‘D’:
cout << “Your average must be between
60 - 69” <<endl;
break;
default:
cout<< “Your average must be below

Course Module: Computer Programming 501


Course
Packet
LM03-EAAC

03 0203

60” <<endl;
}
return 0;
Course Packet 03

Each case keyword is followed by an integer expression


that must be constant, that is, it cannot change in value during
the life of the program. Therefore, a variable cannot follow a case
keyword.

Integer expression is followed by a colon. A common


mistake is to follow the integer expression not with a colon but
with a semicolon, which is typically used to terminate
statements. This will cause a compiler error.

The default keyword serves the same purpose as an else


part in an if/ else if/ else statement. Therefore, is not followed by
an integer expression. The integer expression following the
switch keyword is evaluated and compared with the integer
constant following each case keyword, from top to bottom. If
there is a match, that is the two integers are equal, then the
statements belonging to that case are executed. Otherwise, they
are not.

The statements belonging to a case are conditional, just


as are statements in an if, else if, or else part. Unlike an, if/ else
if/ else statement, multiple conditional statements belonging to a
case do not need to be enclosed in curly braces.

Difference Between switch and if /else if /else Statements

In an if … else if … else statement, the comparison


following the if part may be independent of the comparison
following an else if part.
Example:
if (apples == oranges)
do this;
else if (sales >= 5000)
do that;

Course Module: Computer Programming 502


Course
Packet
LM03-EAAC

03 0203

By contrast, in a switch statement, the constant integer


expression following a case keyword must be compared with the
value following the switch keyword, and nothing else. Another
Course Packet 03

difference is “falling through.” And the other concerns range of


numbers.

Falling Through

In an if … else if … else … statement, each part is


separate from all the others. By contrast, in a switch statement,
unless a break statement is reached, execution “falls through” to
the following case statements that execute their conditional
statements without checking for a match. Falling through
behavior is not necessarily bad.

Sample Program 30:

#include <iostream.h>
int main ()
{
char grade;
cout <<“Enter your grade: ”;
cin >> grade;
switch (grade)
{
case ‘a’:
case ‘A’:
cout << “Your average must be between
90 - 100” <<endl;
break;
case ‘b’:
case ‘B’:
cout << “Your average must be between
80 - 89” <<endl;
break;
case ’c’:
case ‘C’:
cout << “Your average must be between
70 - 79” <<endl;

Course Module: Computer Programming 503


Course
Packet
LM03-EAAC

03 0203

break;
case ‘d’:
case ‘D’:
Course Packet 03

cout << “Your average must be between


60 - 69” <<endl;
break;
default:
cout<< “Your average must be below
60” <<endl;
}
return 0;
}

Sample Program 31:

#include <iostream.h>
int main ()
{
char choice;
cout <<“Choose your car\n ”;
cout <<“S for Standard\n ”;
cout <<“L for Leather Seats\n ”;
cout <<“D for Leather Seats + Chrome Wheels\n ”;
cin >> choice;
cout <<“Extra features purchased\n ”;
switch (choice)
{
case ‘D’:
cout << “Chrome wheels\n”;
case ‘L’:
cout << “Leather seats\n”;
break;
default:
cout << “None selected\n”;
}
return 0;
}

Course Module: Computer Programming 504


Course
Packet
LM03-EAAC

03 0203

Range of Numbers

Another difference between switch and if/else if/else


Course Packet 03

statements concerns the handling of ranges of numbers.


Example:
if (testScore >= 90)
cout << “Your grade is an A” <<endl;
else if (testScore >= 80)
cout << “Your grade is a B” <<endl;
else if (testScore >= 70)
cout << “Your grade is a C” <<endl;
else if (testScore >= 60)
cout << “Your grade is a D” <<endl;
else
cout << “Your grade is an F” <<endl;

A case statement cannot be followed by an expression


such as testScore >= 90 because the case statement keyword has
to be followed by an integer constant.
Example:
switch (testScore)
{
case 100:
case 99:
case 98:
case 97:
case 96:
case 95:
case 94:
case 93:
case 92:
case 91:
case 90:
cout << “Your grade is an A”;
break;
case 89:
case 88:
case 87:
case 86:

Course Module: Computer Programming 505


Course
Packet
LM03-EAAC

03 0203

case 85:
case 84:
case 83:
Course Packet 03

case 82:
case 81:
case 80:
cout << “Your grade is a B”;
break;
}

Nested if Statements

Relational expressions are evaluated one at a time and


choose which of the two codes will execute depending on
whether the expression was true or false. However, sometimes
two (or more) relational expressions need to be evaluated to
determine the code that will execute.
Example:
Voters are only eligible to vote only if they are a citizen
and they are at least 18 years old.
You may get into a movie free if you are either a senior
citizen (65 years or older) or a child (12 or under).

An if statement may appear inside another if statement.


When this is done, the inner if statements are said to be “nested”
inside the outer if statement. A program can have nested if
statements to determine if both of two Boolean expressions are
true, or if either of the expressions is true.
Syntax:
if (conditionO)
if (conditionI)
statement;
else
statement;
else
statement;

Course Module: Computer Programming 506


Course
Packet
LM03-EAAC

03 0203

Testing if Both Boolean Expressions Are True

Sample Program 32:


Course Packet 03

#include <iostream.h>
int main ()
{
int age;
char choice;
bool citizen;
cout << “Enter your age: “;
cin >> age;
cout << “Are you a citizen (Y/N): “;
cin >> choice;
if (choice == ‘Y’)
citizen = true;
else
citizen = false;
if (age >= 18)
if (citizen == true)
cout << “You are eligible to vote “;
else
cout << “You are not eligible to vote “;
else
cout << “You are not eligible to vote “;
return 0;
}

The entire inner if … else structure nested within the if


part of the outer if … else structure.

It is also possible to nest an if … else structure (or an if


structure, or an if … else if … else structure) within the else if or
else part of an outer if … else/if … else if … else/if … else
structure.

Course Module: Computer Programming 507


Course
Packet
LM03-EAAC

03 0203

Testing if Either Boolean Expressions Is True

Sample Program 33:


Course Packet 03

#include <iostream.h>
int main ()
{
int age;
cout << “Enter your age: “;
cin >> age;
if (age > 12)
if (age >= 65)
cout << “Admission is free “;
else
cout << “You have to pay “;
else
cout << “Admission is free “;
return 0;
}
Alternative:
if (age <= 12)
cout << “Admission is free”;
else if (age >= 65)
cout << “Admission is free”;
else
cout << “You have to pay”;

Each of the two alternatives, the nested if statements and


the if … else if … else structure, have disadvantages. Nesting
one if statement inside another by its very nature may be
somewhat difficult to write and understand. However, the if …
else if … else if … else structure has the disadvantage of
repeating the same cout statement for both the if and else if parts.
While this is just one line of repetitive code in this program, in
more complex programs the repetitive code could be many lines
long.

C++ has a third and perhaps better alternative, the use of


logical operators.

Course Module: Computer Programming 508


Course
Packet
LM03-EAAC

03 0203

Logical Operators

C++ has logical operators that enable you to combine


Course Packet 03

comparisons in one if or else if statement.

Table 58. Logical Operators


Operator Name What it does
Connects two relational expressions. Both
&& And expressions must be true for the overall
expression to be true.
Connects two relational expressions. If either
|| Or expression is true, the overall expression is
true.
Reverse the “truth” of an expression, making a
! Not true expression false, and a false expression
true.

The && Operator

The && operator also is known as the logical And


operator. It is a binary operator; it takes two Boolean expressions
as operands. It returns true only if both expressions are true. If
either expression is false, the overall expression is false. If both
expressions are false, the overall expression is false.

Table 59. Logical And


Expression1 Expression2 Expression1 && Expression2
True True True
True False False
False True False
False False False

Sample Program 34:

#include <iostream.h>
int main ()
{
int age;
char choice;
bool citizen;

Course Module: Computer Programming 509


Course
Packet
LM03-EAAC

03 0203

cout << “Enter your age: “;


cin >> age;
cout << “Are you a citizen (Y/N): “;
Course Packet 03

cin >> choice;


if (choice == ‘Y’)
citizen = true;
else
citizen = false;
if (age >= 18 && citizen == true)
cout << “You are eligible to vote “;
else
cout << “You are not eligible to vote “;
return 0;
}

If the left expression is false, the second comparison is


not even made before the else part is executed. The reason is to
avoid wasting CPU time since if the left expression is false, the
overall expression is false regardless of the result of the
evaluation of the right expression.

The || Operator

The || operator also is known as the logical Or operator.


Like the logical And operator, the logical Or operator is also a
binary operator, taking two Boolean expressions as operands. It
returns true if either expression is true. It returns false only if
both expressions are false. If both expressions are true, the
overall expression is true.

Table 60. Logical Or


Expression1 Expression2 Expression1 && Expression2
True True True
True False True
False True True
False False False

Course Module: Computer Programming 510


Course
Packet
LM03-EAAC

03 0203

Sample Program 35:

#include <iostream.h>
Course Packet 03

int main ()
{
int age;
cout << “Enter your age: “;
cin >> age;
if (age <= 12 || age >= 65)
cout << “Admission is free “;
else
cout << “You have to pay “;
return 0;
}

If the left expression is true, the second comparison is not


even made before the else part is executed. The reason, as with
the logical And operator, once again is to avoid wasting CPU
time, since if the left expression is true, the overall expression is
true regardless of the result of the evaluation of the right
expression.

The ! Operator

The ! operator also is known as the logical Not operator.


The logical Not operator inverts the value of the Boolean
expression, returning false if the Boolean expression is true, and
true if the Boolean expression is false.

Table 61. Logical Not


Expression !Expression
True False
False True

Unlike the logical And and Or operators, the logical Not


operator is a unary operator; it takes only one Boolean
expression, not two.

Course Module: Computer Programming 511


Course
Packet
LM03-EAAC

03 0203

Sample Program 36:

#include <iostream.h>
Course Packet 03

int main ()
{
int age;
cout << “Enter your age: “;
cin >> age;
if (! (age > 12 && age < 65))
cout << “Admission is free “;
else
cout << “You have to pay “;
return 0;
}

The Not operator permits the programmer to state a


Boolean expression in a different way that may be more intuitive.
Example:
if (age <= 12 || age >= 65)
if (! (age > 12 && age < 65))

Precedence

Precedence, from highest to lowest, among logical


operators and between them and the relational operators.

Table 62. Precedence between Relational and Arithmetic Operators


Operators
!
Relational operators (>, >=, <, <=, ==, !=)
&&
||

Precedence and the Logical Not Operator

Since the logical Not operator has higher precedence


than the relational operators, the program used to illustrate the
logical Not operator uses an extra set of parentheses.

Course Module: Computer Programming 512


Course
Packet
LM03-EAAC

03 0203

Example:
if (! (age > 12 && age < 65))
if (! age > 12 && age < 65)
Course Packet 03

Precedence and the Logical And and Or Operators

In contrast to the logical Not operator, the logical And


and Or operators rank lower in precedence than the relational
operators. Therefore, parentheses normally are not necessary to
separate the logical And and Not operators from the relational
operators.
Example:
if (age >= 18 && citizen == true)
if ((age >= 18) && (citizen == true))
if (resident == true || citizen == true && age >= 18)
if (resident == true || (citizen == true && age >= 18))
if ((resident == true || citizen == true) && age >= 18)

Using the switch Statement with Logical Operators

The switch statement was cumbersome when dealing


with a range of numbers. The reason was that the case keyword
cannot be followed by a range of numbers because it must
instead be followed by a single integer constant. However, the
switch statement may be used with expressions that use the
logical And or Or operator. The reason is that these expressions
have only one of two possible values, true or false.

True and false are both constants; the value of true is


always true and the value of false is always false. While true and
false are Boolean values, each has a corresponding integer value:
1 and 0. Therefore, the case keyword may be followed by true or
false.
Example:
if (age >= 18 && citizen == true)
cout << “You are eligible to vote “;
else
cout << “You are not eligible to vote “;

Course Module: Computer Programming 513


Course
Packet
LM03-EAAC

03 0203

Alternative:
switch (age >= 18 && citizen == true)
{
Course Packet 03

case true:
cout << “You are eligible to vote “;
break;
case false:
cout << “You are not eligible to vote “;
}

Example:
if (age <= 12 || age >= 65)
cout << “Admission is free “;
else
cout << “You have to pay “;
Alternative:
switch (age <= 12 || age >= 65)
{
case true:
cout << “Admission is free “;
break;
case false:
cout << “You have to pay “;
}

The switch statement can be employed as an alternative


to an if /else or if /else if /else structure in programs that evaluate
Boolean expressions using logical operators.

Course Module: Computer Programming 514


Course
Packet
LM03-EAAC

03 0203

Collaborative Learning Exercise 9


Selection Structures
Collaborative Learning Exercise 9

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with a cover page in our Google Classroom.
Keep your work clean and avoid erasures. Use of pencil is prohibited. Use only a blue ballpoint
pen.

The initial value of the radius of a circle is equal to one unit and each succeeding radius is one
unit greater than the value before it. Draw a flowchart to compute the area of the circle starting
with R=1.0 to R=5.0, then print out each radius and the corresponding area of the circle. Code
the resulting flowchart. (25 points)

Course Module: Computer Programming 515


Course
Packet
LM03-EAAC

03 0203

Laboratory Report 8
Selection Structures
Laboratory Report 8

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with a cover page in our Google Classroom.
Keep your work clean and avoid erasures. Use of pencil is prohibited. Use only a blue ballpoint
pen.

Create a flowchart that finds the sum of the first 50 natural numbers and displays the final sum.
Code the resulting flowchart. (25 points)

Course Module: Computer Programming 516


Course
Packet
LM03-EAAC

03 0203

Practical Exam 8
Selection Structures
Practical Exam 8

(Topics Covered: All the topics in Course Packet 03 of Learning Module 03)

Remember:
The Practical Exam will be administered face-to-face. You are given an hour to answer this
practical exam. This is an individual assessment, therefore, individual submission of answer to
is required. Cheating in any form is highly discouraged, individual submission of the answer
to the Schoology account where this is posted is required.

Course Module: Computer Programming 517


Course
Packet
LM03-EAAC

03 0203

References
C Tutorial. (n.d.). Retrieved from W3schools.in: https://www.w3schools.in/c-tutorial/intro/
References

C++ Language. (2000). Retrieved June 27, 2016, from cplusplus.com:


http://www.cplusplus.com/doc/tutorial/

Doyle, B. (2014). C# Programming From Problem Analysis to Program Design Fourth Edition. New
Tech Park, Singapore: Cengage Learning Asia Pte Ltd.

Kent, J. (2005). C++ Demystified. USA: Mc Graw Hill Osborne.

Savitch, W. (1996). Problem Solving with C++ The Object of Programming. California, USA:
Addison-Wesley Publishing Company, Inc.

Schildt, H. (1992). Turbo C/C++: The Complete Reference, Second Edition. California, USA:
Osborne Mc-Graw Hill.

Sellappan, P. (2001). C++ Through Examples. Selangor Darul Ehsan, Malaysia: Federal
Publication Sdn. Berhad.

tutorialspoint. (2020). (Tutorials Point (I) Pvt. Ltd.) Retrieved July 3, 2020, from
https://www.tutorialspoint.com/cprogramming/index.htm

Course Module: Computer Programming 518


Course
Packet
LM03-EAAC

03 0203

Learner’s Feedback Form


Learner’s Feedback Form

Name of Student: _____________________________________________________________


Program : _____________________________________________________________
Year Level : ________ Section : _____ Sex at Birth: ___________
Faculty : _____________________________________________________________
Schedule : _____________________________________________________________

Course Packet : Code : _________ Title : __________________________________

How do you feel about the topic or concept presented?


 I completely get it.  I’m struggling.
 I’ve almost got it.  I’m lost.

In what particular portion of this course packet, do you feel that you are struggling or lost?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Did you raise your concern to your instructor?  Yes  No

If Yes, what did he/she do to help you?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

If No, state your reason?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

To further improve this course packet, what part do you think should be enhanced?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

How do you want it to be enhanced?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Course Module: Computer Programming 519


Course
Packet
LM03-EAAC

03
04 0203

Learning Module 03

Computer
Programming Using C
Language
Course Packet 04

Repetition Structures

Knowledge Area Code : EAAC


Course Code : EAAC0203
Learning Module Code : LM03-EAAC0203
Course Packet Code : LM03-EAAC0203-04

Course Module: Computer Programming 520


Course
Packet
LM03-EAAC

04 0203

Course Packet 04
Course Packet 04

Repetition Structures
Introduction

This course packet introduces the students to the different repetition structures and
increment and decrement operators to be used in a C program. Repetition structure’s function
and their syntax will be discussed with the students to familiarize themselves in its usage and
be able to manipulate the flow of the process in a program. Increment and decrement operators
with relation to other operators will also be discussed and demonstrated to give students
hands-on experience in data and process manipulation in a C program.

Objectives

At the end of the course packet, the students will be able to:
• Make use of the different repetition structures to manipulate the process flow of a C
program.
• Create gender-responsive source code of different programming problems with the help
of a flowchart and pseudocode.

Learning Management System

BSIE 2A Google Classroom Link: https://classroom.google.com/c/NjYzMzg4ODQwNjQ2?cjc=y6oon7r


BSIE 2B Google Classroom Link: https://classroom.google.com/c/NjQ4NzU0MTY5Mzg0?cjc=l7pdjyy
BSCE 1B Google Classroom Link: https://classroom.google.com/c/NjYzNDMzMzg1MDU1?cjc=xoylla6

Duration

• Topic 04: Repetition Structures = 12 hours


(9 hours self-directed learning and 3 hours assessment)

Delivery Mode

Course Packet 4, Repetition Structures, will be delivered via onsite learning (face-to-face),
online learning (synchronous) and offsite learning (asynchronous).

Assessment with Rubrics

The following criteria and the corresponding percentage shall be used to assess the
collaborative learning exercises and laboratory reports as an assessment tool or task.

Criteria Description %
Able to execute calculations correctly by hand and
Calculation apply appropriate mathematical 50%
equations/formulas.
Solution All the answers are correct and properly labeled. 20%

Course Module: Computer Programming 521


Course
Packet
LM03-EAAC

04 0203

Written work is presented neatly and


Neatness 10%
professionally.
Document Submitted work conforms to the prescribed
Course Packet 04

10%
Formatting format.
Work is submitted on or before the specified date
Timeliness 10%
and time.
TOTAL 100%

Requirement with Rubrics

Each student is required to accomplish the collaborative learning exercise and laboratory report
found after reading the course packet. The accomplished collaborative learning exercise and
laboratory report should be posted or submitted at the Google Classroom stream page of the
class on the scheduled date to be given by the faculty in charge.

Readings

1. C++ Demystified by Jeff Kent


2. C++ Through Examples by Dr. Palaniappan Sellappan
3. C# Programming from Problem Analysis to Program Design by Barbara Doyle
4. Turbo C/C++ The Complete Reference Second Edition by Herbert Schildt
5. https://www.tutorialspoint.com/cprogramming/index.htm
6. https://www.w3schools.in/c-tutorial/intro/

Course Module: Computer Programming 522


Course
Packet
LM03-EAAC

04 0203

Introduction
Key Points:

Repetition allows the programmer to efficiently use


Course Packet 04

• C programming
variables. It can structure programming statements to be language assumes any
non-zero and non-null
repeated as long as specific conditions are met. For example, a values as true, and if it
program can input, add, and average multiple numbers using a is either zero or null,
then it is assumed as
limited number of variables. There are three looping structures false value.
in C, the for loop, while loop, and do...while Loop. • Repetition structures,
or loops, are used
when a program needs
Lesson Proper to repeatedly process
one or more
instructions until some
Repetition Structure condition is met, at
which time the loop
ends.
In the world of programming, sometimes there is a need
to repeat the execution of code multiple times. For example, if Definition of Terms:

the user enters invalid data, the program may ask the user Function call. A control
whether they want to retry or quit. If they retry and still enter structure that is used to
invite or call a piece of
invalid data, the program will again ask the user whether they code or statement. In this
want to retry or quit. This process keeps repeating until the user case control jumps from
main program to that
either enters valid data or quits. piece of code and then
returns back to main
program.
Use a loop to repeat the execution of code statements. A Repetition Structures. A
loop in C++ is a structure that repeats the execution of code until control structure where
the statements are
a condition becomes false. The process of performing the same
executed more than one
task over and over again is called iteration, and C++ provides time. It is also known as
iteration or loop.
built-in iteration functionality. A loop executes the same section
Selection Structures. A
of program code over and over again, as long as a loop condition control structure that
of some sort is met with each iteration. This section of code can selects a statement to
execute on the basis of
be a single statement or a block of statements (a compound condition. Statement is
statement). executed when the
condition is true and
ignored when it is false.
Increment and Decrement Operators Sequential Structures. A
control structure that is
executed in a specified
Increment means to increase a value by one while order. No statement is
skipped and executed
decrement means to decrease a value by one. C++ has an more than once.
increment operator that can be used to increase a value by one
and a decrement operator that can be used to decrease a value by
one.

Course Module: Computer Programming 523


Course
Packet
LM03-EAAC

04 0203

The Increment Operator

Sample Program 37:


Course Packet 04

#include <iostream.h>
int main()
{
int num = 2;
num += 1;
cout << num;
return 0;
}

Another way to accomplish the same result is by using


the increment operator, ++. The increment operator is unary, that
is it operates on one operand. The operand generally is a whole
number variable.

Sample Program 38:

#include <iostream.h>
int main ()
{
int num = 2;
num++;
cout << num;
return 0;
}
Alternative:
#include <iostream.h>
int main ()
{
int num = 2;
++num;
cout << num;
return 0;
}

Course Module: Computer Programming 524


Course
Packet
LM03-EAAC

04 0203

Placing the ++ before a variable is called prefix


incrementing, the “pre” indicating that the increment operator
precedes its operand. Placing the ++ after a variable is called
Course Packet 04

postfix incrementing, the “post” indicating that the increment


operator follows its operand. It makes no difference to the
output of a program whether it uses prefix or postfix
incrementing. The reason is that the statement has only one
operator. However, there is a difference between prefix and
postfix incrementing when the statement has more than one
operator.

The Decrement Operator

Sample Program 39:

#include <iostream.h>
int main ()
{
int num = 2;
num -= 1;
cout << num;
return 0;
}

Another way to accomplish the same result is by using


the decrement operator, --. Decrement operator, like the
increment operator, is unary, operating on one operand which
generally is a whole number variable.

Sample Program 40:

#include <iostream.h>
int main ()
{
int num = 2;
num--;
cout << num;
return 0;
}

Course Module: Computer Programming 525


Course
Packet
LM03-EAAC

04 0203

Alternative:
#include <iostream.h>
int main ()
Course Packet 04

{
int num = 2;
--num;
cout << num;
return 0;
}

As with the increment operator, placing the -- before a


variable is called prefix decrementing, while placing the – after a
variable is called postfix decrementing. It makes no difference to
the output of a program whether it uses prefix or postfix
decrementing. The reason is that the statement has only one
operator. However, there is a difference between prefix and
postfix decrementing when the statement has more than one
operator.

The Difference Between Prefix and Postfix

Sample Program 41:

#include <iostream.h>
int main ()
{
int num = 2;
cout << num++;
return 0;
}

Sample Program 42:

#include <iostream.h>
int main ()
{
int num = 2;
cout << num++;
return 0;

Course Module: Computer Programming 526


Course
Packet
LM03-EAAC

04 0203

There are two operators in the cout statement: the


Course Packet 04

increment operator ++ and the stream insertion operator <<. The


issue is one of precedence; which operation occurs first. When
an increment or decrement operator is postfix, that operation is
the last to occur. When an increment or decrement operator is
prefixed, that operation is the first to occur.

The distinction between prefix and postfix also arises


frequently with arithmetic operators.
Example:
int op1 = 3, op2 = 5, result;
result = op1 * op2++;
Multiplication and assignment occur first in postfix
incrementing and decrementing.
Example:
int op1 = 3, op2 = 5, result;
result = op1 * ++op2;
Multiplication and assignment occur last in prefix incrementing
and decrementing.

The distinction between prefix and postfix arises as well


with relational operators.
Example:
int num = 5;
cout << (num++ == 5);
Relational comparison occurs first in postfix incrementing and
decrementing.
Example:
int num = 5;
cout << (++num == 5);
Relational comparison occurs last in prefix incrementing and
decrementing.

Increment and decrement operators generally are not


used by themselves but in conjunction with loops.

Course Module: Computer Programming 527


Course
Packet
LM03-EAAC

04 0203

The for Loop

Sample Program 43:


Course Packet 04

#include <iostream.h>
int main ()
{
int num = 1;
cout << num++;
cout << num++;
cout << num++;
cout << num++;
cout << num++;
cout << num++;
cout << num++;
cout << num++;
cout << num++;
cout << num++;
return 0;
}

The same program could be written with far less code by


using a for loop.

Sample Program 44:

#include <iostream.h>
int main ()
{
for (int num = 1; num <= 10; num++)
cout << num << “ “;
return 0;
}
Another Program:
#include <iostream.h>
int main ()
{
for (int num = 1; num <= 100; num++)
cout << num << “ “;

Course Module: Computer Programming 528


Course
Packet
LM03-EAAC

04 0203

return 0;
}
Course Packet 04

The for loop is one of the three types of loops; the other
two are the while and do while loop. A loop is a structure that
repeats the execution of code until a condition becomes false.
Each repetition is called an iteration.
Syntax:
for (initialization; condition; update)
statement;

The for keyword is followed by parentheses that contain


three expressions. This line of code is followed by one or more
statements. The three expressions contained in the parentheses
following the for keyword are separated by semicolons; there is
no semicolon after the third expression since no expression
follows it.

The first expression usually is used to initialize the value


of a variable, typically referred to as a counter, to provide that
variable with a starting value. Initialization is the first action
performed by the loop. The initialization that occurred during
the first iteration of the loop will not occur during the second
iteration of the loop. Initialization occurs only once, in the first
iteration of the loop.

The second expression is the condition, which must be


true for the code inside the loop to execute. The third expression
usually is used to update the value of the counter. This
expression executes at the end of each iteration and only executes
if the condition was true at the beginning of the iteration. Postfix
and prefix incrementing will output the same result since only
one operator is involved in the expression.

As with the if structure, if more than one statement


belongs to the for loop, then the statements must be contained
within curly braces.
Example:
for (int num = 1; num <= 10; num++)

Course Module: Computer Programming 529


Course
Packet
LM03-EAAC

04 0203

{
cout << num << “ “;
cout << “Next Loop “;
Course Packet 04

}
Also, as with the if structure, the statement or statements
following the for keyword and parentheses will not execute if the
parentheses are followed by a semi-colon since that would be
interpreted as an empty statement.
Example:
for (int num = 1; num <= 10; num++);
cout << num << “ “;
The expressions do not need to be inside the parentheses
following the for loop.

Sample Program 45:

#include <iostream.h>
int main ()
{
int num = 1;
for (; num <= 10;)
{
cout << num << “ “;
num++;
}
return 0;
}
Even though initialization and incrementing are not done within
the parentheses, two semicolons are nevertheless within the
parentheses to separate where the three expressions would be.

Sample Program 46:


#include <iostream.h>
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";
}

Course Module: Computer Programming 530


Course
Packet
LM03-EAAC

04 0203

cout << "FIRE!";


return 0;
}
Course Packet 04

Beware the Infinite Loop

Sample Program 47:

#include <iostream.h>
int main ()
{
int num = 1;
for(; num <= 10;)
{
cout << num << “ ”;
}
return 0;
}

The loop that never stops executing is called an infinite


loop. It manifests itself by a character or characters appearing in
rapid succession in the console window, with the application
never-ending. Use the CTRL+BREAK keyboard combination to
end the program.

Breaking Out of a Loop

As with the switch statement, the break keyword can


also be used in a for loop. The break keyword is used within the
code of a for loop, commonly within an if … else structure. If the
break keyword is reached, the for loop terminates, even though
the condition still is true.

Sample Program 48:

#include <iostream.h>
int main ()
{
int num, counter, secret = 3;

Course Module: Computer Programming 531


Course
Packet
LM03-EAAC

04 0203

cout << “Guess a number between 1 and 10\n“;


cout << “You have 3 trials\n“;
for (int counter = 1; counter <= 3; counter++)
Course Packet 04

{
cout << “Enter the number now: “;
cin >> num;
if (num == secret)
{
cout << “You guessed the secret
number!”;
break;
}
}
cout << “Program over”;
return 0;
}

Normally, the for loop has one exit point, the condition
when it becomes false. However, when one or more break
statements are used, the for loop has multiple exit points. The
disadvantage of using a break in a for loop is that it makes the
code difficult to understand, and can result in logic errors.

Sample Program 49:

#include <iostream.h>
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;

Course Module: Computer Programming 532


Course
Packet
LM03-EAAC

04 0203

The logical && (And) operator is an alternative to using


Course Packet 04

the break keyword.

Sample Program 50:

#include <iostream.h>
int main ()
{
int num, counter, secret = 3;
cout << “Guess a number between 1 and 10\n “;
cout << “You have 3 trials\n “;
bool keepgoing = true;
for (int counter = 1; counter <= 3 && keepgoing ==
true; counter++)
{
cout << “Enter the number now: “;
cin >> num;
if (num == secret)
{
cout << “You guessed the secret
number!”;
keepgoing = false;
}
}
cout << “Program over”;
return 0;
}

One additional use of break keyword is in conjunction


with the parentheses following the for keyword being empty of
all three expressions.

Sample Program 51:

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

Course Module: Computer Programming 533


Course
Packet
LM03-EAAC

04 0203

int num = 1;
for ( ; ; )
{
Course Packet 04

if (num > 10)


break;
else
{
cout << num << “ ”;
num++;
}
}
return 0;
}

Without the break keyword, the for loop would be


infinite due to the lack of a second expression

The continue Keyword

The continue keyword can also be used in a for loop. The


continue keyword, like the break keyword, is used within the
code of a for loop, commonly within an if … else structure. If the
continue statement is reached, the current iteration of the loop
ends, and the next iteration of the loop begins.

Sample Program 52:

#include <iostream.h>
int main ()
{
int num, counter, total = 0;
cout << “How many items do you want to buy: “;
cin >> num;
for ( int counter = 1; counter <= num; counter++ )
{
if (counter % 4 == 0)
continue;
total += 3;
}

Course Module: Computer Programming 534


Course
Packet
LM03-EAAC

04 0203

cout << “Total for “<< num << “ items is $” << total;
return 0;
}
Course Packet 04

Normally, each iteration of a for loop has one endpoint.


However, when a continue statement is used, each iteration has
multiple endpoints. The logical ! (Not) operator is an alternative
to using the continue keyword.

Sample Program 53:

#include <iostream.h>
int main ()
{
int num, counter, total = 0;
cout << “How many items do you want to buy: “;
cin >> num;
for (int counter = 1; counter <= num; counter++)
{
if (!(counter % 4 == 0))
total += 3;
}
cout << “Total for “ << num << “ items is $” << total;
return 0;
}
It is possible to use the relational != (not equal) operator,
changing the if statement to if (counter % 4 != 0).

Sample Program 54:

#include <iostream.h>
int main ()
{
for (int n=10; n>0; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!";

Course Module: Computer Programming 535


Course
Packet
LM03-EAAC

04 0203

return 0;
}
Course Packet 04

Nesting for Loops

Syntax:
for (expressionO1; expressionO2; expressionO3)
{
for (expressionI1; expressionI2; expressionI3)
statementI;
statementO;
}

Can nest a for loop just as the programmer can nest if


statements.

Sample Program 55:

#include <iostream.h>
int main ()
{
for (int x = 1; x <= 5; x++)
{
for (int y = 1; y <= 10; y++)
cout << “X“;
cout << “\n”;
}
return 0;
}

With nested for loops, for each iteration of the outer for
loop, the inner for loop goes through all its iterations.

Sample Program 56:

#include <iostream.h>
int main ()
{
for (int x = 1; x <= 5; x++)

Course Module: Computer Programming 536


Course
Packet
LM03-EAAC

04 0203

{
for (int y = 1; y <= 10; y++)
cout << “X“;
Course Packet 04

cout << “\n”;


}
return 0;
}

While nested for loops can be used to print rows and


columns for tables, they also have other uses.

Sample Program 57:

#include <iostream.h>
int main ()
{
int persons, int numSales;
cout << “Enter number of salespersons: “;
cin >> persons;
cout << “Enter number of sales per salesperson: “;
cin >> numSales;
for (int x = 1; x <= persons; x++)
{
int sale, total = 0;
float average;
for (int y = 1; y <= numSales; y++)
{
cout << “Enter sale “<< y << “ for
salesperson “ << x << “: “;
cin >> sale;
total += sale;
}
average = (float) total / numSales;
cout << “Average sales for salesperson #” << x
<< “ is “ << average << endl;
}
return 0;
}

Course Module: Computer Programming 537


Course
Packet
LM03-EAAC

04 0203

If a break or continue keyword is placed in the inner


loop, it will affect only that inner loop, and do not affect the outer
loop.
Course Packet 04

The for loop generally is used when the loop will iterate
a fixed number of times. However, sometimes the number of
times a loop will iterate is unpredictable, depending on user
input during runtime. While the total number of loop iterations
may be unpredictable, there often are situations in which the
loop will iterate at least once.

The while Loop

The while loop is similar to a for loop in that both have


the typical characteristics of a loop, the code inside each
continues to iterate until a condition becomes false. The
difference between them is in the parentheses following the for
and while keywords. The parentheses following the for
keyword consists of three expressions, initialization, condition,
and update. By contrast, the parentheses following the while
keyword consists only of the condition, any initialization and
update can be elsewhere in the code.

Sample Program 58:

#include <iostream.h>
int main ()
{
for (int num = 1; num <= 10; num++)
cout << num << “ “;
return 0;
}
Alternative:
#include <iostream.h>
int main ()
{
int num = 1;
while (num <= 10)
{

Course Module: Computer Programming 538


Course
Packet
LM03-EAAC

04 0203

cout << num << “ “;


num++;
}
Course Packet 04

return 0;
}
The two statements in the body of the while loop could have been
combined into one statement, cout << num++.

With the while loop, the variable had to be declared and


initialized before the loop since this cannot be done inside the
parentheses following the while keyword. Further, the variable
was updated inside the code of the loop using the increment
operator. This update also can be done inside the parentheses
following the while keyword.
Syntax:
initialization;
while (condition)
{
statement/s;
update;
}
or
initialization;
while (conditionupdate)
statement;
or
initialization;
while (condition)
statementupdate;

The update of the variable is particularly important with


the while loop. Without that update, the loop would be infinite.
Example:
int num = 1;
while (num <= 10)
cout << num << “ “;
If more than one statement belongs to the while loop, then the
statements must be contained within curly braces.

Course Module: Computer Programming 539


Course
Packet
LM03-EAAC

04 0203

Example:
while (num <= 10)
{
Course Packet 04

cout << num << “ “;


num++;
}
The update could also be done within the condition itself.

Sample Program 59:

#include <iostream.h>
int main ()
{
int num = 0;
while (num++ < 10)
cout << num << “ “;
return 0;
}

Updating the counter within the condition requires two


changes. The value of the variable has to be initialized to 0
instead of 1 because the increment inside the parentheses during
the first iteration of the loop would change the variable’s value
to 1. The relational operator in the condition is changed.
As with the for loop, the statement or statements following the
while keyword and parentheses will not execute if the
parentheses are followed by a semicolon, as that would be
interpreted as an empty statement.
Example:
while (num <= 10);
cout << num++ << “ “;

Sample Program 60:

#include <iostream.h>
int main ()
{
int n;
cout << "Enter the starting number > ";

Course Module: Computer Programming 540


Course
Packet
LM03-EAAC

04 0203

cin >> n;
while (n>0)
{
Course Packet 04

cout << n << ", ";


--n;
}
cout << "FIRE!";
return 0;
}

Comparison of for and while loops

The practical difference between the for and while loops


is not apparent in a program with a predictable number of
iterations. A while loop is a superior choice to a for loop in a
program where the number of iterations is unpredictable,
depending on user input during runtime.

Sample Program 61:

#include <iostream.h>
int main ()
{
int num;
cout << “Enter a positive number: “;
cin >> num;
while (num <= 0)
{
cout << “Number must be positive; please
retry: “;
cin >> num;
}
cout << “The number you entered is “<< num << “ “;
return 0;
}

Course Module: Computer Programming 541


Course
Packet
LM03-EAAC

04 0203

Using the break Keyword

While the user should be required to enter good data if


Course Packet 04

they are going to enter any data at all, they should have the
option, when told the data entered was not valid, of quitting the
data entry.

Sample Program 62:

#include <iostream.h>
int main ()
{
int num;
char choice;
cout << “Enter a positive number: “;
cin >> num;
while (num <= 0)
{
cout << “Number must be positive; try again
(Y/N): “;
cin >> choice;
if (choice == ‘Y’)
{
cout << “Enter number: “;
cin >> num;
}
else
break;
}
cout << “The number you entered is “<< num << “ “;
return 0;
}

Flags

Ideally, a program should output the data if it were


valid. If the data were not valid, then the program should output
the fact instead. Use the break keyword sparingly because it
creates multiple exit points for the while loop, making the code

Course Module: Computer Programming 542


Course
Packet
LM03-EAAC

04 0203

more difficult to understand and increasing the possibility of


logic errors. As an alternative, use a logical operator.
Course Packet 04

Sample Program 63:

#include <iostream.h>
int main ()
{
int num;
char choice;
bool quit = false;
cout << “Enter a positive number: “;
cin >> num;
while (num <= 0 && quit == false)
{
cout << “Number must be positive; try again
(Y/N): “;
cin >> choice;
if (choice == ‘Y’)
{
cout << “Enter number: “;
cin >> num;
}
else
quit = true;
}
if (quit == false)
cout << “The number you entered is “<< num
<< “ “;
else
cout << “You did not enter a positive number”;
return 0;
}

A flag is a Boolean variable whose value indicates


whether a condition exists. A common programming mistake in
a while condition using a logical operator is to use && when you
should use || or vice versa.

Course Module: Computer Programming 543


Course
Packet
LM03-EAAC

04 0203

While (true)

Programmers sometimes make the condition of the


Course Packet 04

while loop always true, such as while (true) or while (1), and
break out of the while loop with the break keyword. The use of
the while (true) syntax has the disadvantage of making the code
less readable because the condition that stops the loop cannot be
discerned from the parentheses following the while keyword.
The do while loop avoids this disadvantage and would be a
preferable choice.

Sample Program 64:

#include <iostream.h>
int main ()
{
int num;
char choice;
bool quit = false;
while (true)
{
cout << “Enter a positive number: “;
cin >> num;
if (num > 0)
break;
else
{
cout << “Number must be positive; try
again (Y/N): “;
cin >> choice;
if (choice != ‘Y’)
{
quit = true;
break;
}
}
}
if (quit == false)
cout << “The number you entered is “<< num

Course Module: Computer Programming 544


Course
Packet
LM03-EAAC

04 0203

<< “ “;
else
cout << “You did not enter a positive number“;
Course Packet 04

return 0;
}

The continue Keyword

Use the continue keyword in a while loop just as it can


be used in a for loop. The continue keyword, like the break
keyword, is used within the code of a loop, commonly within an
if … else structure. If the continue statement is reached, the
current iteration of the loop ends, and the next iteration of the
loop begins.

Sample Program 65:

#include <iostream.h>
int main ()
{
int num, counter = 0, total = 0;
cout << “How many items do you want to buy: “;
cin >> num;
while (counter++ < num)
{
if (counter % 13 == 0)
continue;
total += 3;
}
cout << “Total for “<< num << “ items is $” << total;
return 0;
}

Use continue keyword sparingly. Normally, each


iteration of a for loop has one endpoint. However, when the
programmer uses a continue statement, each iteration has
multiple endpoints. This makes the code more difficult to
understand, and can result in logic errors. Use the logical ! (Not)
operator as an alternative to using the continue keyword.

Course Module: Computer Programming 545


Course
Packet
LM03-EAAC

04 0203

Sample Program 66:

#include <iostream.h>
Course Packet 04

int main()
{
int num, counter = 0, total = 0;
cout << “How many items do you want to buy: “;
cin >> num;
while (counter++ < num)
{
if (!(counter % 13 == 0))
total += 3;
}
cout << “Total for “ << num << “ items is $” << total;
return 0;
}

Nesting while Loops

The programmer can nest one while loop inside another.


Also, can nest a while loop inside of a for loop, or a for loop inside
of a while loop.
Syntax:
initializationO;
while(conditionO)
{
initializationI;
while(conditionI)
{
statement/sI;
updateI;
}
statement/sO;
updateO;
}

Sample Program 67:

#include <iostream.h>

Course Module: Computer Programming 546


Course
Packet
LM03-EAAC

04 0203

int main ()
{
int x = 0;
Course Packet 04

while (x++ < 5)


{
int y = 0;
while (y++ < 5)
cout << “X”;
cout << “\n”;
}
return 0;
}

The do while Loop

The do while loop is similar to the while loop. The


primary difference is that with a do while loop the condition is
tested at the bottom of the loop, unlike a while loop where the
condition is tested at the top. A do while loop will always
execute at least once, whereas a while loop may never execute at
all if its condition is false at the outset.
Syntax:
initialization;
do
{
statement/s;
update;
} while (condition);
or
do
{
statementupdate;
} while (condition);
or
do
{
statement/s;
} while (conditionupdate);

Course Module: Computer Programming 547


Course
Packet
LM03-EAAC

04 0203

The do keyword starts the loop. The statement or


statements belonging to the loop are enclosed in curly braces.
After the close curly braces, the while keyword appears,
Course Packet 04

followed by the condition in parentheses, terminated by a


semicolon.

Sample Program 68:

#include <iostream.h>
int main ()
{
int num;
char choice;
bool quit = false;
do {
cout << “Enter a positive number: “;
cin >> num;
if (num <= 0)
{
cout << “Number must be positive; try
again (Y/N): “;
cin >> choice;
if (choice != ‘Y’)
quit = true;
}
} while (num <= 0 && quit == false);
if (quit == false)
cout << “The number you entered is “<< num
<< “ “;
else
cout << “You did not enter a positive number“;
return 0;
}

Sample Program 69:

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

Course Module: Computer Programming 548


Course
Packet
LM03-EAAC

04 0203

unsigned long n;
do {
cout << "Enter number (0 to end): ";
Course Packet 04

cin >> n;
cout << "You entered: " << n << "\n";
} while (n != 0);
return 0;
}

Comparison of the Do While and While Loop

Prefer a do while loop over a while loop in situations in


which the loop must execute at least once before a condition may
be tested, simply because under these circumstances it seems
illogical to test the condition prematurely on the first iteration of
the loop. A do while loop normally is preferable to a while loop
when choosing a loop to display a menu.

Scope

With a do while loop, it is important that a variable used


in the condition following the while keyword not be declared
inside the loop.
Example:
int num;
char choice;
bool quit = false;
do {
// statements;
} while (num <= 0 && quit == false);

Variables could not be declared inside the do while loop


because the code would not compile. The parentheses following
the while keyword is highlighted, and the compiler error is that
variables are undeclared identifiers.
Example:
char choice;
do {
int num;

Course Module: Computer Programming 549


Course
Packet
LM03-EAAC

04 0203

bool quit = false;


// more statements
} while (num <= 0 && quit == false);
Course Packet 04

The reason is the variable scope. A variable must be declared


before it can be referred to in code. Once a variable is declared,
it may be referred to wherever in the code it has scope.

Variables have been declared in main, just after the open


curly brace which begins the body of the main function. This
gives the variable scope until the close curly brace, which ends
the body of the main function. The area between an open and
closed curly brace is referred to as a block. This issue arises far
more often with the do while loop than with the for or while
loops.

With for or while loops, the condition precedes the body


of the loop, so any variables used in the condition necessarily
would be declared before the loop or, in case of the for loop,
within the parentheses following the for keyword. By contrast,
since the condition of a do while loop comes after the body of the
loop, it is an easy mistake to declare the variables used in the
condition before it, in the body of the loop.

Nesting do while Loops

The programmer can nest one do while loop inside


another. Also, can nest a do while loop inside of a for loop or
while loop, or a for loop or while loop inside of a do while loop.
Syntax:
initializationO;
do {
initializationI;
do {
statement/sI;
updateI;
} while(conditionI);
statement/sO;
updateO;
} while(conditionO);

Course Module: Computer Programming 550


Course
Packet
LM03-EAAC

04 0203

Sample Program 70:

#include <iostream.h>
Course Packet 04

int main ()
{
int x = 0;
do {
int y = 0;
do {
cout << “X”;
} while (y++ < 5);
cout << “\n”;
} while (x++ < 5);
return 0;
}

Jump Statements

In addition to the sequences, repetition, and selection


constructs, C++ also provides jump statements. It allows
program control to be transferred from one part of the program
to another unconditionally. C++ has four jump statements which
are break, goto, continue, and return.

The break Statement

If executed, it terminates the structure that contains it. A


general rule is, a break terminates the nearest enclosing switch
or loop.
Example:
for (sum = 0, count = 0; ; count++)
{
cout << “\n Enter a positive number (1 to
terminate) ”;
cin >> data;
if (data < 0) break;
sum = sum + data;
}

Course Module: Computer Programming 551


Course
Packet
LM03-EAAC

04 0203

The continue Statement

The continue statement can only be used inside a loop


Course Packet 04

and not a switch. When executed, it transfers control to the test


condition in a while or a do while loop, and to the increment
expression in a for loop. It forces the next iteration to take place
immediately, skipping any instructions that may follow it.
Unlike the break statement, continue does not force the
termination of a loop, it merely transfers control to the next
iteration.
Example:
for (I = 1, sum = 0; i<100; i++)
{
if (i % 2) continue;
sum = sum + 1;
}

The goto Statement

The goto statement has a form that uses a label which is


any valid C++ identifier followed by a colon (:) and must be
placed in the same function.
Syntax:
goto label:
Example:
sum = 0;
i = 0;
next:
i++;
cout << “\n Enter next number: “;
cin >> data;
sum += data;
if (i < 20) goto next;
cout << “\nSum = “<< sum;

The frequent use of the goto statement is usually not


recommended because its use could result in ‘spaghetti’ codes
that will be difficult to debug. However, it could be very useful
in certain situations such as exiting from a deeply nested loop.

Course Module: Computer Programming 552


Course
Packet
LM03-EAAC

04 0203

The return Statement

The effect of executing a return statement is to terminate


Course Packet 04

the execution of the current function and pass the return value
contained in the expression (if any) to the function that invoked
it. The value returned must be of the same type or convertible to
the same type as the function. If necessary, more than one return
statement may be placed in a function. The execution of the first
return statement in the function automatically terminates the
function.
Syntax:
return expression;

Sample Program 71:

# include <iostream.h>
int main ()
{
float y1, y2, avgy;
float avg (float, float);
y1 = 5.0;
y2 = 7.0;
avgy = avg (y1, y2);
cout << “\nThe average = “ <<avgy;
return 0;
}
float avg (float x1, float x2)
{
float avgx;
avgx = (x1 + x2)/2;
return avgx;
}

Course Module: Computer Programming 553


Course
Packet
LM03-EAAC

04 0203

Collaborative Learning Exercise 10


Repetition Structures
Collaborative Learning Exercise 10

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with a cover page in our Google Classroom.
Keep your work clean and avoid erasures. Use of pencil is prohibited. Use only a blue ballpoint
pen.

Given a set of 5 numbers that include both positive and negative data values. Draw a flowchart
to read in these values one at a time and count the number of positive values (including zero
values) and the number of negative values found in the set. After the required values are
determined, print out these counted values. Code the resulting flowchart. (40 points)

Course Module: Computer Programming 554


Course
Packet
LM03-EAAC

04 0203

Laboratory Report 9
Repetition Structures
Laboratory Report 9

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with a cover page in our Google Classroom.
Keep your work clean and avoid erasures. Use of pencil is prohibited. Use only a blue ballpoint
pen.

Create the flowchart that will produce the figure below. Code the resulting flowchart. (45
points)

Course Module: Computer Programming 555


Course
Packet
LM03-EAAC

04 0203

Practical Exam 9
Repetition Structures
Practical Exam 9

(Topics Covered: All the topics in Course Packet 04 of Learning Module 03)

Remember:
The Practical Exam will be administered face-to-face. You are given an hour to answer this
practical exam. This is an individual assessment, therefore, individual submission of answer to
is required. Cheating in any form is highly discouraged.

Course Module: Computer Programming 556


Course
Packet
LM03-EAAC

04 0203

References
C Tutorial. (n.d.). Retrieved from W3schools.in: https://www.w3schools.in/c-tutorial/intro/
References

C++ Language. (2000). Retrieved June 27, 2016, from cplusplus.com:


http://www.cplusplus.com/doc/tutorial/

Doyle, B. (2014). C# Programming From Problem Analysis to Program Design Fourth Edition. New
Tech Park, Singapore: Cengage Learning Asia Pte Ltd.

Kent, J. (2005). C++ Demystified. USA: Mc Graw Hill Osborne.

Savitch, W. (1996). Problem Solving with C++ The Object of Programming. California, USA:
Addison-Wesley Publishing Company, Inc.

Schildt, H. (1992). Turbo C/C++: The Complete Reference, Second Edition. California, USA:
Osborne Mc-Graw Hill.

Sellappan, P. (2001). C++ Through Examples. Selangor Darul Ehsan, Malaysia: Federal
Publication Sdn. Berhad.

tutorialspoint. (2020). (Tutorials Point (I) Pvt. Ltd.) Retrieved July 3, 2020, from
https://www.tutorialspoint.com/cprogramming/index.htm

Course Module: Computer Programming 557


Course
Packet
LM03-EAAC

04 0203

Learner’s Feedback Form


Learner’s Feedback Form

Name of Student: _____________________________________________________________


Program : _____________________________________________________________
Year Level : ________ Section : _____ Sex at Birth: ___________
Faculty : _____________________________________________________________
Schedule : _____________________________________________________________

Course Packet : Code : _________ Title : __________________________________

How do you feel about the topic or concept presented?


 I completely get it.  I’m struggling.
 I’ve almost got it.  I’m lost.

In what particular portion of this course packet, do you feel that you are struggling or lost?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Did you raise your concern to your instructor?  Yes  No

If Yes, what did he/she do to help you?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

If No, state your reason?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

To further improve this course packet, what part do you think should be enhanced?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

How do you want it to be enhanced?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Course Module: Computer Programming 558


Course
Packet
LM03-EAAC

04
05 0203

Learning Module 03

Computer
Programming Using C
Language
Course Packet 05

Functions and Arrays

Knowledge Area Code : EAAC


Course Code : EAAC0203
Learning Module Code : LM03-EAAC0203
Course Packet Code : LM03-EAAC0203-05

Course Module: Computer Programming 559


Course
Packet
LM03-EAAC

05 0203

Course Packet 05
Course Packet 05

Functions and Arrays


Introduction

This course packet introduces the students to the function and array construction to be
used in a C program. Creating, defining, and calling a function as well as the different ways of
passing data to and from different functions will be discussed to the students to familiarize
themselves in its usage and be able to manipulate the flow of data in a program. Different uses
of arrays will also be discussed and demonstrated to give students hands-on experience in data
manipulation in a C program.

Objectives

At the end of the course packet, the students will be able to:
• Make use of functions and arrays to manipulate the data and process flow of a C program.
• Create the gender-responsive source code of different programming problems with the
help of flowchart and pseudocode.

Learning Management System

BSEE 1C Google Classroom Link: https://classroom.google.com/c/NjYzNDQ1NDE2NTAx?cjc=e55hvj2


BSEE 1D Google Classroom Link: https://classroom.google.com/c/NjYzNDQzMDU2MTI0?cjc=fbfpl6c

Duration

• Topic 05: Function and Arrays = 12 hours


(6 hours self-directed learning and 6 hours assessment)

Delivery Mode

Course Packet 5, Function and Arrays will be delivered via onsite learning (face-to-face), online
learning (synchronous) and offsite learning (asynchronous).

Assessment with Rubrics

The following criteria and the corresponding percentage shall be used to assess the
collaborative learning exercises and laboratory reports as assessment tool or task.

Criteria Description %
Able to execute calculations correctly by hand and
Calculation apply appropriate mathematical 50%
equation/formula.
Solution All the answers are correct and properly labeled. 20%
Written work is presented neatly and
Neatness 10%
professionally.

Course Module: Computer Programming 560


Course
Packet
LM03-EAAC

05 0203

Document Submitted work conforms to the prescribed


10%
Formatting format.
Work is submitted on or before the specified date
Course Packet 05

Timeliness 10%
and time.
TOTAL 100%

Requirement with Rubrics

Each student is required to accomplish the collaborative learning exercise and laboratory report
found after reading the course packet. The accomplished collaborative learning exercise and
laboratory report should be posted or submitted at the Google Classroom stream page of the
class on the scheduled date to be given by the faculty-in-charge.

Readings

1. C++ Demystified by Jeff Kent


2. C++ Through Examples by Dr. Palaniappan Sellappan
3. C# Programming from Problem Analysis to Program Design by Barbara Doyle
4. Turbo C/C++ The Complete Reference Second Edition by Herbert Schildt
5. https://www.tutorialspoint.com/cprogramming/index.htm
6. https://www.w3schools.in/c-tutorial/intro/

Course Module: Computer Programming 561


Course
Packet
LM03-EAAC

05 0203

Introduction
Key Points:

In C, a large program can be divided into the basic


Course Packet 05

• A function is a block of
building blocks known as function. A large C program can easily code that performs a
specific task.
be tracked when it is divided into multiple functions. Also, by • While creating a C
using functions, programmer can avoid rewriting same logic or function, give a
definition of what the
code again and again in a program. C functions can also be called
function has to do. To
any number of times in a program and from any place in a use a function, call that
function to perform the
program that provide reusability and modularity in a program.
defined task.
• The size and type of
An array is used to store a collection of data, but it is an array cannot be
changed once it is
often more useful to think of an array as a collection of variables declared.
of the same type. Instead of declaring individual variables, such
Definition of Terms:
as num0, num1, ..., and num99, programmer can declare one
array variable such as num and use num[0], num[1], and ..., Array. Arrays a kind of
data structure that can
num[99] to represent individual variables. A specific element in store a fixed-size
an array is accessed by an index. sequential collection of
elements of the same
type.
Lesson Proper Function call. A control
structure that is used to
invite or call a piece of
Function code or statement. In this
case control jumps from
main program to that
A function is a group of statements that together piece of code and then
returns back to main
perform a task. Programmer can divide up the code into
program.
separate functions. How to divide up the code among different Repetition Structures. A
functions is up to the programmer, but logically the division control structure where
the statements are
usually is so each function performs a specific task. For example, executed more than one
a program that performs arithmetic calculations, one function time. It is also known as
iteration or loop.
obtains user input, another function performs the calculation, Selection Structures. A
and a third function performs output of the result. control structure that
selects a statement to
execute on the basis of
There are advantages to dividing the code into separate condition. Statement is
executed when the
functions in addition to making the code easier to understand. condition is true and
For example, if a function performs a specific task, such as ignored when it is false.
Sequential Structures. A
sending output to a printer, which is performed several times in control structure that is
a program, the programmer only needs to write once in a executed in a specified
order. No statement is
function the code necessary to send output to the printer, and skipped and executed
then call that function each time the programmer needs to more than once.
perform that task.

Course Module: Computer Programming 562


Course
Packet
LM03-EAAC

05 0203

Defining and Calling a Function

Implementing any function in addition to main involves


Course Packet 05

two steps which are defining the function and calling the
function.

Terminology of a Function

Sample Program 72:

#include <iostream.h>
int main ()
{
cout << “Hello World!”;
return 0;
}

The first line, int main (), is the function header. Unlike
a statement, the function header is not followed by a semicolon.
The function header consists of a return type, a function name,
and an argument list. The data type int preceding main is the
return type, main is the function name, and the parentheses (),
empty but not always, contains the argument list. A function
header always is followed by an open curly brace, which begins
the function body.

The function body ends with a close curly brace. The


function body consists of one or more statements. The last
statement is a return statement. The function body must contain
a return statement unless the return type is void, in which case
the return statement is optional. The function header and body
together are referred to as the function definition.

A function cannot execute until it is first defined. Once


defined, a function executes when it is called. A function is called
through code. The main function is the exception. The main
function is called automatically when the program begins to run.

Course Module: Computer Programming 563


Course
Packet
LM03-EAAC

05 0203

Defining a Function

Sample Program 73:


Course Packet 05

#include <iostream.h>
void printMessage (void)
{
cout << “Hello World!”;
}
int main ()
{
printMessage();
return 0;
}

The function is defined first. The void keyword


preceding the function name means that this function does not
return a value. The void keyword in parentheses following the
function name means this function has no arguments. The
parentheses also could be left empty, such as after main; empty
parentheses following the function name in a function header is
the same as placing the void keyword within the parentheses.
The function body does not need to contain an explicit return
statement because, since the return type is void, the return
statement is implied.
Example:
void printMessage (void)
{
cout << “Hello World!”;
return;
}

Calling a Function

Unless the function is called, it is there in the program,


but it doesn’t do anything.
Example:
printMessage ();
printMessage is the called function, since it is the function being

Course Module: Computer Programming 564


Course
Packet
LM03-EAAC

05 0203

called from main. The empty parentheses indicate that no


arguments are being passed to this function. The order of
execution is:
Course Packet 05

1. Execution always starts with the main function.


2. The first statement in main, printMessage (), is executed.
Execution next shifts to the printMessage() function, and begins
with the first statement in that function. After the printMessage
function completes executing, execution returns to the main
function with the next unexecuted statement, return 0, which
completes the main function.

Prototyping

Since execution always starts with main, it seems more


logical to place the main function first, ahead of a function.

Sample Program 74:

#include <iostream.h>
int main ()
{
printMessage();
return 0;
}
void printMessage (void)
{
cout << “Hello World!”;
}

The code will not compile. The call in main to a function


will be highlighted, with the compiler error message being
“undeclared identifier”. When the compiler, going from top to
bottom in the code, encounters a function call, it must already
know of the function’s name, return type, and arguments. Which
is not a problem when the function was defined above the main
function. One solution is to define all functions above main. But
it makes the code difficult to read. In a program with many
functions, the main function often acts as a “switchboard”,
calling one function after another.

Course Module: Computer Programming 565


Course
Packet
LM03-EAAC

05 0203

The solution of preference is to prototype each function,


except main, which does not have to be prototyped since it is
required by every program.
Course Packet 05

Sample Program 75:

#include <iostream.h>
void printMessage (void);
int main ()
{
printMessage ();
return 0;
}
void printMessage (void)
{
cout << “Hello World!”;
}

The prototype is above all function definitions. It


ensures that the compiler, compiling the code from top to
bottom, will encounter the prototype before any function. The
prototype is similar to a function header. The primary difference
is that it has a semicolon at the end because it is a statement. By
contrast, a function header must not be followed by a semicolon.

Variable Scope and Lifetime

All variables have been defined at the top of the main


function. In programs where the only function is main, those
variables can be accessed throughout the entire program since
main is the entire program. However, once the code is separated
into functions, issues arise concerning variable scope and
lifetime.

Local Variables

The programmer can call the same function multiple


times. However, once the code is separated into functions, issues
arise concerning variable scope and lifetime.

Course Module: Computer Programming 566


Course
Packet
LM03-EAAC

05 0203

Sample Program 76:

#include <iostream.h>
Course Packet 05

void printMessage(void);
int main ()
{
int times = 0;
char choice;
do {
cout << “Enter Q to quit, any other character to
continue: “;
cin >> choice;
if (choice == ‘Q’)
cout << “Input stopped”;
else
printMessage ();
} while (choice != ‘Q);
return 0;
}
void printMessage (void)
{
times ++;
cout << “This function called “<< times << “ times\n” ;
}

The code will not compile. The reference to the variable


in the function will be highlighted, the error message being that
this variable is an “undeclared identifier”. The reason for the
compiler error is that the scope of the variable is limited to the
main function in which it was declared. The variable is local to
the main function. An attempt to access a local variable outside
of the function in which it was declared results in a compiler
error.

Sample Program 77:

#include <iostream.h>
void printMessage(void);
int main ()

Course Module: Computer Programming 567


Course
Packet
LM03-EAAC

05 0203

{
char choice;
do {
Course Packet 05

cout << “Enter Q to quit, any other character to


continue: “;
cin >> choice;
if (choice == ‘Q’)
cout << “Input stopped”;
else
printMessage ();
} while (choice != ‘Q);
return 0;
}
void printMessage (void)
{
int times = 0;
times ++;
cout << “This function called “<< times << “ times\n” ;
}

The variable in the function does not “remember” the


previous times that function was called. Variables have a
lifetime. A variable’s lifetime begins when it is declared. A
variable’s lifetime ends when it goes out of scope. Being a local
variable in a function, each time the function is called, the
variable is created, and each time the function ends, the variable
is destroyed. There are two alternative methods to having the
value of a variable persist between function calls:
1. One is to make the variable global rather than local.
2. The other is to keep the variable local but make it static.

Global Variables

A variable may be global instead of local. The term


global means that the variable has scope throughout the
program. Since the variable has scope throughout the program,
its lifetime does not end until the program ends. To make a
variable global, it must be declared above all function
definitions, generally with function prototypes.

Course Module: Computer Programming 568


Course
Packet
LM03-EAAC

05 0203

Sample Program 78:

#include <iostream.h>
Course Packet 05

void printMessage(void);
int times;
int main ()
{
times = 0;
char choice;
do {
cout << “Enter Q to quit, any other character to
continue: “;
cin >> choice;
if (choice == ‘Q’)
cout << “Input stopped”;
else
printMessage ();
} while (choice != ‘Q);
return 0;
}
void printMessage (void)
{
times ++;
cout << “This function called “<< times << “ times\n” ;
}

A global variable can be accessed throughout the


program. The fact that a global variable can be accessed and
changed anywhere in the program makes it more difficult to
determine why a global variable has an invalid value than if the
variable’s scope was far more limited. One alternative is to make
the variable static.

Static Local Variables

A variable’s lifetime was dictated by its scope. Since a


local variable’s scope was limited to the function in which it was
declared, the local variable’s lifetime ended when that function
ended. Since a global variable had scope throughout a program,

Course Module: Computer Programming 569


Course
Packet
LM03-EAAC

05 0203

the global variable’s lifetime did not end until the entire program
ended. A static local variable is different.
Course Packet 05

A static local variable has the scope of a local variable


but the lifetime of a global variable. A static local variable is
declared exactly like a local variable, within a function rather
than above all functions as with a global variable. The difference
between the declaration of a static local variable and a non-static,
or automatic, local variable is that a static local variable is
declared with the static keyword, and usually also with a starting
value.
Example:
int times; → local and global declaration
static int times = 0; → static local declaration

Sample Program 79:

#include <iostream.h>
void printMessage(void);
int times;
int main ()
{
char choice;
do {
cout << “Enter Q to quit, any other character to
continue: “;
cin >> choice;
if (choice == ‘Q’)
cout << “Input stopped”;
else
printMessage ();
} while (choice != ‘Q);
return 0;
}
void printMessage (void)
{
static int times = 0;
times ++;
cout << “This function called “<< times << “ times\n” ;

Course Module: Computer Programming 570


Course
Packet
LM03-EAAC

05 0203

When the function ends, the static local variable is not


Course Packet 05

destroyed. That variable and its value remain in memory.

Sending Information to A Function

Sample Program 80:

#include <iostream.h>
#include <string.h>
void printMessage(void);
string str;
int main ()
{
cout << “Enter a string: “;
cin >> str;
printMessage ();
return 0;
}
void printMessage ()
{
cout << “You inputted “<< str;
}

The parentheses following the function name in the


function header contain the function’s argument. Arguments are
information that is provided to a function so that it may perform
its task.

Passing Arguments by Value

The content of the message to be output is passed to the


function as an argument.

Sample Program 81:

#include <iostream.h>
#include <string.h>

Course Module: Computer Programming 571


Course
Packet
LM03-EAAC

05 0203

void printMessage(string);
int main ()
{
Course Packet 05

string str;
cout << “Enter a string: “;
cin >> str;
printMessage (str);
return 0;
}
void printMessage (string s)
{
cout << “You inputted “<< s;
}

The Function Prototype and Header

Both the function prototype and the function header


have one argument. The function’s prototype’s argument just
has the argument’s data type, whereas the function header’s
argument has both a data type and an argument name. The
function prototype may include an argument name as well as
data type.
Example:
void printMessage (string someArg);
However, the argument is called a dummy argument because it
serves no purpose. By contrast, the function header’s argument
must include an argument name as well as a data type.

Using the Function Argument

The function header must include an argument name as


well as a data type so the value which is being passed by the
function call may be stored in a variable that can be used in the
function. The argument name in the function header can be the
same as the name of the variable passed in the function
argument. It may also be different.
Example:
printMessage (str);
void printMessage (string str)

Course Module: Computer Programming 572


Course
Packet
LM03-EAAC

05 0203

or
printMessage (str);
void printMessage (string s)
Course Packet 05

Using Multiple Function Arguments

A function may have two or even more function


arguments.

Sample Program 82:

#include <iostream.h>
#include <string.h>
void printMessage(string, string,int);
int main ()
{
string name1, name2;
int a=0;
cout << “Enter the first name: “;
cin >> name1;
cout << “Enter the second name: “;
cin >> name2;
printMessage (name1, name2, a);
return 0;
}
void printMessage (string firstName, string lastName, int x)
{
cout << “Your name is “<< firstName << “ “
<< lastName << endl<<x;
}

The order of arguments in the function call must


correspond to the order of the arguments in the function header.
The consequences of a lack of correspondence between the order
of arguments in the function call and the order of the arguments
in the function header is more drastic when the multiple function
arguments have different data types.

Course Module: Computer Programming 573


Course
Packet
LM03-EAAC

05 0203

Sample Program 83:

#include <iostream.h>
Course Packet 05

#include <string.h>
void printMessage (string, int);
int main ()
{
string name;
int age;
cout << “Enter the first name: “;
cin >> name1;
cout << “Enter the second name: “;
cin >> name2;
cout << “Enter name: “;
cin >> name;
cout << “Enter age: “;
cin >> age;
printMessage(name, age);
return 0;
}
void printMessage (string theName, int theAge)
{
cout << “Your name is “<< theName << “ and your age
is “ << theAge << endl;
}

Passing Arguments by Reference

Passing arguments by value is fine when the value does


not change in the called function. However, sometimes the
intent of a function is to change the value of the argument passed
to it.

Sample Program 84:

#include <iostream.h>
void doubleIt(int);
int main ()
{

Course Module: Computer Programming 574


Course
Packet
LM03-EAAC

05 0203

int num;
cout << “Enter number: “;
cin >> num;
Course Packet 05

doubleIt(num);
cout << “The number doubled in main is “ << num
<< endl;
return 0;
}
void doubleIt (int x)
{
cout << “The number to be doubled is “ << x << endl;
x *= 2;
cout << “The number doubled in doubleIt is “ << x
<< endl;
}

In order for the called function to change the value in


main of a variable passed to it, the variable must be passed by
reference. The variable in the called function is called a reference
variable. The reference variable is not a copy of the variable in
main. Instead, the reference variable is an alias for the variable in
main. In order to pass a variable by reference, the data type in
the argument, both in the function header and in the prototype,
is followed by an ampersand.

Sample Program 85:

#include <iostream.h>
void doubleIt(int&);
int main ()
{
int num;
cout << “Enter number: “;
cin >> num;
doubleIt(num);
cout << “The number doubled in main is “<< num
<< endl;
return 0;
}

Course Module: Computer Programming 575


Course
Packet
LM03-EAAC

05 0203

void doubleIt (int& x)


{
cout << “The number to be doubled is “<< x << endl;
Course Packet 05

x *= 2;
cout << “The number doubled in doubleIt is “<< x
<< endl;
}

However, the function call is the same whether the


variable is passed by value or by reference; there is no
ampersand in either case.

Whether the program passes an argument in a function


call by value or by reference is dictated by the function’s
prototype. A program can pass multiple values by reference as
well as by value. Indeed, the programmer can pass some values
by reference and others by value. Pass by reference those values
need to change, and pass by value those values that are not
changing. There is another difference between passing by value
and passing by reference. The programmer can pass by value
expression and constants as well as variables. However, the
programmer can only pass variables by reference.

Sample Program 86:

#include <iostream.h>
void addNumbers (int, int, int&);
int main ()
{
int firstNum, secondNum, sum = 0;
cout << “Enter first number: “;
cin >> firstNum;
cout << “Enter second number: “;
cin >> secondNum;
addNumbers(firstNum, secondNum, sum);
cout << firstNum << “ + “ << secondNum << “ = “
<< sum;
return 0;
}

Course Module: Computer Programming 576


Course
Packet
LM03-EAAC

05 0203

void addNumbers (int x, int y, int& z)


{
z = x + y;
Course Packet 05

Returning A Value from A Function

Arguments are used to pass values to a called function.


A return value can be used to pass a value from a called function
back to the function that called it.

Sample Program 87:

#include <iostream.h>
int addNumbers (int, int);
int main ()
{
int firstNum, secondNum, sum = 0;
cout << “Enter first number: “;
cin >> firstNum;
cout << “Enter second number: “;
cin >> secondNum;
sum = addNumbers (firstNum, secondNum);
cout << firstNum << “ + “ << secondNum << “ = “
<< sum;
return 0;
}
int addNumbers (int x, int y)
{
return x + y;
}

The return value is added by indicating its data type in


front of the function name in both the function prototype and
header. The function call is on the right side of the assignment
operator. To the left of the assignment operator is a variable of
the same data type as the return value of the function. The body
of the called function has the return keyword followed by a value
of the data type compatible with the function prototype and

Course Module: Computer Programming 577


Course
Packet
LM03-EAAC

05 0203

header. The function’s return value is the value that follows the
return keyword.
Course Packet 05

It is common that a function returning a value is called


on the right side of an assignment operator with a variable on the
left side of the assignment operator to capture the return value.
However, this is not required.
Example:
sum = addNumbers (firstNum, secondNum);
cout << firstNum << “ + “ << secondNum << “ = “ << sum;
cout << firstNum << “ + “ << secondNum << “ = “
<< addNumbers (firstNum, secondNum);
The only difference is that once this cout statement completes,
the return value of the function cannot be used in later
statements since it was not stored in a variable.

If the program is going to use a return value more than


once, it’s generally a good idea to store that return value in a
variable. This is typically done by calling the function on the
right side of an assignment operator with a variable on the left
side of the assignment operator to capture the return value.
While multiple values can be passed to a function as arguments,
at this point, multiple values cannot be returned from functions
using the data types.

Array

An array enables the programmer to use a single


variable to store many values. The values are stored at
consecutive indexes, starting with zero and then incrementing by
one for each additional element of the array. Using 1 array
variable to store many values has many advantages over having
to declare separate variables that can hold only 1 value each.

In addition to being a lot less code to write, it is far easier


to keep track of 1 variable than many variables. Furthermore,
and more important, programmer can use a loop to access each
consecutive element in an array, whereas this is not possible with
three separate variables.

Course Module: Computer Programming 578


Course
Packet
LM03-EAAC

05 0203

Declaring an Array

An array is a variable. Like other variables, an array


Course Packet 05

must be declared before it can be used.


Syntax:
datatype var[size_indicator];
The syntax for declaring an array is almost identical to the syntax
for declaring integers, characters, or other variables.
Example:
int testScore; → integer variable
int testScore [3]; → integer array variable
float GPA [5];
char grades [7];
string names [6];

While an array may be one of several data types, all the


values in a particular array must be of the same data type. The
program cannot have an array in which some elements are floats,
others are strings, still others are integers, and so on. The
declaration of both a single variable and an array of variables
begins with the data type followed by a variable name and
ending with a semicolon. The only difference between declaring
a variable that holds a single value and an array is that, when
declaring an array, the variable name is followed by a number
within square brackets. That number is the array’s size indicator.

The purpose of the size declarator is to tell the computer


how much memory to reserve. The size declarator, combined
with the data type of the array, determines how much memory
to reserve. Give careful consideration to the number of elements
in an array before declaring the array since an array cannot be
resize in the middle of a program in the event the array is too
small or unnecessarily large. There is one exception to the
necessity of having a size declarator. The square brackets may be
empty if you initialize the array when you declare it.

Constants

Each of the size declarators used was a literal. A literal

Course Module: Computer Programming 579


Course
Packet
LM03-EAAC

05 0203

is a value that is written exactly as it is meant to be interpreted.

Sample Program 88:


Course Packet 05

#include <iostream.h>
int main ()
{
int testScore[3];
return 0;
}

The size declarator may not be a variable. The result is a


compiler error. The compiler will flag the declaration of the array
and complain that a constant expression was expected. It is
possible to declare the size of an array with a variable if you use
a different array declaration technique, dynamic memory
allocation.

Sample Program 89:

#include <iostream.h>
int main ()
{
int numTests;
cout << “Enter the number of test scores:”;
cin >> numTests;
int testScore[numTests];
return 0;
}

A constant is a name that represents the same value


throughout a program. A constant is the converse of a variable,
while a variable is a name that may represent different values
during the execution of a program. However, the value of a
constant cannot change during the execution of a program.
While neither a literal nor a constant change its value during the
execution of a program, they are not the same. While a constant
is a name that represents a value, a literal is not a name, but
instead the value itself.

Course Module: Computer Programming 580


Course
Packet
LM03-EAAC

05 0203

May use a constant instead of a literal as a size


declarator.
Course Packet 05

Sample Program 90:

#include <iostream.h>
int main ()
{
const int numTests = 3;
int testScore[numTests];
return 0;
}

The syntax for declaring a constant is similar to, but not


the same as, a syntax for declaring a variable. Each requires a
data type and a variable name and ends in a semicolon.
However, there are two differences. First, the declaration of a
constant must begin with the const keyword. This tells the
compiler that you are declaring a constant instead of a variable.
Second, the declaration terminates by assigning the constant a
value. Assigning a variable with a value when it is declared is
optional. On the other hand, assigning a constant a value when
declaring it is mandatory.

The declaration of the constant will not compile if it is


not assigned a value. The compiler error being that a constant
object must be initialized. The programmer cannot assign a
value of a constant after an array is declared, the only time to
assign a value to a constant is when it is declared. The
declaration of a constant does reserve memory just as does the
declaration of a variable. The difference is that with a constant
the value stored at the memory address cannot change during
the life of the program.

Sample Program 91:

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

Course Module: Computer Programming 581


Course
Packet
LM03-EAAC

05 0203

const int numTests = 3;


cout << “Enter the number of test scores:”;
cin >> numTests;
Course Packet 05

int testScore[numTests];
return 0;
}

The result is a compiler error. The compiler will flag the


attempt to assign a value to the constant and complain that the
stream extraction operator >> cannot have a right-hand operand
that is a constant.

Sample Program 92:

#include <iostream.h>
int main ()
{
const int numTests = 3;
int num;
cout << “Enter the number of test scores:”;
cin >> num;
numTest = num;
int testScore[numTests];
return 0;
}

The result is a compiler error. The compiler will flag the


attempt to assign a value to the constant; the error message will
be that “l-value specifies const object”. The l in “l-value” refers
to the value to the left of the assignment operator.

The reason to use a constant instead of a literal array to


declare the size of an array is that, in the code the programmer
may need to often refer to the size of the array, not only when
declaring it, but also when assigning values to, and displaying
them from, the array. However, the needs of the program may
require to modify the code to change the size of the array, usually
to make it larger. Use a constant to change the value in the code

Course Module: Computer Programming 582


Course
Packet
LM03-EAAC

05 0203

in just one place. Constant have many uses in addition to


signifying the size of an array.
Course Packet 05

Array Index

The entire array has only one name. The programmer


needs to be able to refer to individual elements of the array.
Refer to the individual elements of the array by their position
within the array. This position is referred to as an index or
subscript. The first index in an array is always 0. The last index
in an array is always 1 less than the number of elements in the
array. There are no exceptions.

The fact that the first index in an array is 0 instead of 1 is


because of an offset. An offset refers to a value added to a base
address to produce a second address. The base address of an
array is the address where the array begins. The address of the
first element of the array is the same as the base address of the
array itself. Therefore, the value that would be added to the base
address of the array to obtain the address of the first element of
the array is 0, which is the index of the first element of the array.
The address of any element of the array is the base address of the
array plus the offset, and in turn the offset is determined by the
index of the array multiplied by the size of the array’s data type.
Since the first index in an array must always be 0, the last index
in an array must always be 1 less than the number of elements in
the array.

Initialization

Initialization is when a value is assigned to a variable in


the same statement in which the variable is declared.
Assignment on the other hand is assigning a value to a variable
in a statement after the declaration statement. There are two
alternative methods in initializing an array. First is explicit array
sizing in which the square brackets contain a numerical constant
that explicitly specifies the size of the array.
Example:
int testScore[3] = {74, 87,92};

Course Module: Computer Programming 583


Course
Packet
LM03-EAAC

05 0203

float milesPerGallon[4] = {44.4, 22.3, 11.6, 33.3};


char grades[5] = {‘A’, ‘B’, ‘C’, ‘D’, ‘F’};
string days[7] = {“Sunday”, “Monday”, “Tuesday”,
Course Packet 05

“Wednesday”, “Thursday”, “Friday”, “Saturday”};


Second is implicit array sizing in which the square brackets are
empty and the size of the array is indicated implicitly by the
number of elements on the right side of the assignment operator.

Course Module: Computer Programming 584


Course
Packet
LM03-EAAC

05 0203

Collaborative Learning Exercise 11


Functions and Arrays
Collaborative Learning Exercise 11

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with a cover page in our Google Classroom.
Keep your work clean and avoid erasures. Use of pencil is prohibited. Use only blue ballpoint
pen.

Create the flowchart of the program that will combine the programs done in CLE 8, 9, and 10
and Laboratory Report 7, 8, and 9. The program will prompt the user to choose which program
to run. The program should utilize function, also array if necessary, for code division. The
main function should only contain the data input and display. The processing should happen
in other functions. (30 points)

Course Module: Computer Programming 585


Course
Packet
LM03-EAAC

05 0203

Laboratory Report 10
Functions and Arrays
Laboratory Report 10

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with a cover page in our Google Classroom.
Keep your work clean and avoid erasures. Use of pencil is prohibited. Use only blue ballpoint
pen.

Code the flowchart of the program that will combine the programs done in CLE 8, 9, and 10
and Laboratory Report 7, 8, and 9. The program will prompt the user to choose which program
to run. The program should utilize function, also array if necessary, for code division. The
main function should only contain the data input and display. The processing should happen
in other functions. (65 points)

Course Module: Computer Programming 586


Course
Packet
LM03-EAAC

05 0203

Practical Exam 10
Functions and Arrays
Practical Exam 10

(Topics Covered: All the topics in Course Packet 05 of Learning Module 3)

Remember:
The Practical Exam will be administered face-to-face. You are given an hour to answer this
practical exam. This is an individual assessment, therefore, individual submission of answer to
is required. Cheating in any form is highly discouraged.

Course Module: Computer Programming 587


Course
Packet
LM03-EAAC

05 0203

References
C Tutorial. (n.d.). Retrieved from W3schools.in: https://www.w3schools.in/c-tutorial/intro/
References

C++ Language. (2000). Retrieved June 27, 2016, from cplusplus.com:


http://www.cplusplus.com/doc/tutorial/

Doyle, B. (2014). C# Programming From Problem Analysis to Program Design Fourth Edition. New
Tech Park, Singapore: Cengage Learning Asia Pte Ltd.

Kent, J. (2005). C++ Demystified. USA: Mc Graw Hill Osborne.

Savitch, W. (1996). Problem Solving with C++ The Object of Programming. California, USA:
Addison-Wesley Publishing Company, Inc.

Schildt, H. (1992). Turbo C/C++: The Complete Reference, Second Edition. California, USA:
Osborne Mc-Graw Hill.

Sellappan, P. (2001). C++ Through Examples. Selangor Darul Ehsan, Malaysia: Federal
Publication Sdn. Berhad.

tutorialspoint. (2020). (Tutorials Point (I) Pvt. Ltd.) Retrieved July 3, 2020, from
https://www.tutorialspoint.com/cprogramming/index.htm

Course Module: Computer Programming 588


Course
Packet
LM03-EAAC

05 0203

Learner’s Feedback Form


Learner’s Feedback Form

Name of Student: _____________________________________________________________


Program : _____________________________________________________________
Year Level : ________ Section : _____ Sex at Birth: ___________
Faculty : _____________________________________________________________
Schedule : _____________________________________________________________

Course Packet : Code : _________ Title : __________________________________

How do you feel about the topic or concept presented?


 I completely get it.  I’m struggling.
 I’ve almost got it.  I’m lost.

In what particular portion of this course packet, do you feel that you are struggling or lost?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Did you raise your concern to your instructor?  Yes  No

If Yes, what did he/she do to help you?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

If No, state your reason?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

To further improve this course packet, what part do you think should be enhanced?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

How do you want it to be enhanced?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Course Module: Computer Programming 589


Course
Packet
LM03-EAAC

05
06 0203

Learning Module 03

Computer
Programming Using C
Language
Course Packet 06

Graphics Manipulation

Knowledge Area Code : EAAC


Course Code : EAAC0203
Learning Module Code : LM03-EAAC0203
Course Packet Code : LM03-EAAC0203-06

Course Module: Computer Programming 590


Course
Packet
LM03-EAAC

06 0203

Course Packet 06
Course Packet 06

Graphics Manipulation
Introduction

This course packet introduces the students to the different commands to be used to
create a graphical design in a C program. The graphics command’s function and their syntax
will be discussed to the students to familiarize themselves in its usage and be able to
manipulate the output screen. Different graphical manipulation will also be discussed and
demonstrated to give students hands-on experience in output screen manipulation in a C
program.

Objectives

At the end of the course packet, the students will be able to:
• Make use of the different graphics commands to manipulate the output screen using a C
program.
• Create the gender-responsive source code of different programming problems with the
help of flowchart and pseudocode.

Learning Management System

BSIE 2A Google Classroom Link: https://classroom.google.com/c/NjYzMzg4ODQwNjQ2?cjc=y6oon7r


BSIE 2B Google Classroom Link: https://classroom.google.com/c/NjQ4NzU0MTY5Mzg0?cjc=l7pdjyy
BSCE 1B Google Classroom Link: https://classroom.google.com/c/NjYzNDMzMzg1MDU1?cjc=xoylla6

Duration

• Topic 06: Graphics Manipulation = 12 hours


(6 hours self-directed learning and 6 hours assessment)

Delivery Mode

Course Packet 6, Graphics Manipulation, will be delivered via onsite learning (face-to-face),
online learning (synchronous) and offsite learning (asynchronous).

Assessment with Rubrics

The following criteria and the corresponding percentage shall be used to assess the
collaborative learning exercises and laboratory reports as assessment tool or task.

Criteria Description %
Able to execute calculations correctly by hand and
Calculation apply appropriate mathematical 50%
equation/formula.
Solution All the answers are correct and properly labeled. 20%

Course Module: Computer Programming 591


Course
Packet
LM03-EAAC

06 0203

Written work is presented neatly and


Neatness 10%
professionally.
Document Submitted work conforms to the prescribed
Course Packet 06

10%
Formatting format.
Work is submitted on or before the specified date
Timeliness 10%
and time.
TOTAL 100%

Requirement with Rubrics

Each student is required to accomplish the collaborative learning exercise and laboratory report
found after reading the course packet. The accomplished collaborative learning exercise and
laboratory report should be posted or submitted at the Google Classroom stream page of the
class on the scheduled date to be given by the faculty-in-charge.

Readings

1. C++ Demystified by Jeff Kent


2. C++ Through Examples by Dr. Palaniappan Sellappan
3. C# Programming from Problem Analysis to Program Design by Barbara Doyle
4. Turbo C/C++ The Complete Reference Second Edition by Herbert Schildt
5. https://www.tutorialspoint.com/cprogramming/index.htm
6. https://www.w3schools.in/c-tutorial/intro/

Course Module: Computer Programming 592


Course
Packet
LM03-EAAC

06 0203

Introduction
Key Points:

Graphics programming in C is used to draw various


Course Packet 06

• In a C program, first
geometrical shapes such as rectangle, circle, ellipse and step is to initialize the
graphics drivers on the
polygons, to draw curves using mathematical function, to color computer. This is done
an object with different colors and patterns, and simple using the initgraph ()
method provided in
animation programs like jumping ball and moving cars. graphics.h library.

Definition of Terms:
Lesson Proper
Computer Graphics.
Computer graphics is the
Turbo C Graphics
use of computers to
create and manipulate
Turbo C is an Integrated Development Environment and pictures or image or
drawings on a display
compiler for the C programming language from Borland. It was device. It comprises of
first introduced in 1987 and was noted for its integrated software techniques to
create, store, modify,
development environment, small size, fast compile speed, represents pictures or
comprehensive manuals and low price. In May 1990, Borland image or drawings.
DOSBox. DOSBox is a
replaced Turbo C with Turbo C++. free and open-source
emulator of an Intel x86
personal computer
C graphics using graphics.h functions can be used to designed for the purpose
draw different shapes, display text in different fonts, change of running software
created for disk operating
colors and many more. Using functions of graphics.h in Turbo systems on IBM PC
C compiler you can make graphics programs, animations, compatibles, primarily
DOS video games.
projects, and games. Programmer can draw circles, lines, Turbo C. Turbo C is a C
rectangles, bars and many other geometrical figures. Programming Language
compiler that transforms
Programmer can also change their colors using the available
programs written in C to
functions and fill them. Assembly or Machine
code to create an
executable Program.
How to Use DOSBox or TurboCdroid TurboCdroid.
TurboCdroid is specially
designed for
1. Open DOSBox or TurboCdroid. School/college students to
2. Go to File and select DOS Shell. run Turbo C++ on android
platform.
3. In DOS Shell change the directory from bin to bgi to run
graphics mode.
C:\TC\BIN>cd..
C:\TC>cd bgi
C:\TC\BGI>exit
4. Go to File and select New to start a new program

Course Module: Computer Programming 593


Course
Packet
LM03-EAAC

06 0203

#include<graphics.h>

It is the include directive that is used to draw different


Course Packet 06

shapes, display text in different fonts, change colors and many


more. Using it in Turbo C compiler can make graphics programs,
animations, projects, and games or can draw circles, lines,
rectangles, bars and many other geometrical figures. It can
change their colors using the available functions and fill them.
Syntax:
#include<graphics.h>

clrscr()

It is a predefined function in "conio.h" (console input


output header file) used to clear the console screen. It is a
predefined function, by using this function it can clear the data
from console (Monitor). Using of clrscr() is always optional but
it should be place after variable or function declaration only.
Syntax:
clrscr();

getch()

It is a nonstandard function and is present in conio.h


header file which is mostly used by MS-DOS compilers like
Turbo C. This function prompts a user to press a character in the
keyboard and that character is not printed on screen.
Syntax:
getch();

initgraph()

It initializes the graphics system by loading a graphics


driver from disk (or validating a registered driver), and putting
the system into graphics mode. It also resets or initializes all
graphics settings like color, palette, current position etc., to their
default values.
Syntax:
initgraph(int *graphdriver, int *graphmode, char

Course Module: Computer Programming 594


Course
Packet
LM03-EAAC

06 0203

*pathtodriver);

The graphdriver is a pointer to an integer specifying the


Course Packet 06

graphics driver to be used. It tells the compiler that what


graphics driver to use or to automatically detect the drive. Use
DETECT macro of graphics.h library that instruct compiler for
auto detection of graphics driver. The graphmode is a pointer to
an integer that specifies the graphics mode to be used. If *gdriver
is set to DETECT, then initgraph sets *gmode to the highest
resolution available for the detected driver. The pathtodriver
specifies the directory path where graphics driver files (BGI files)
are located. If directory path is not provided, then it will search
for driver files in current working directory. Change path of BGI
directory accordingly where the Turbo C++ compiler is installed.

cleardevice()

The function which clears the screen in graphics mode


and sets the current position to (0,0). Clearing the screen consists
of filling the screen with current background color.
Syntax:
cleardevice();

closegraph()

The function which closes the graphics mode,


deallocates all memory allocated by graphics system and
restores the screen to the mode it was in before the initgraph was
called.
Syntax:
closegraph();

setcolor()

The function which is used to set the current drawing


color to the new color. In Turbo C graphics each color is assigned
a number. Total of 16 colors are available.
Syntax:
setcolor(int color);

Course Module: Computer Programming 595


Course
Packet
LM03-EAAC

06 0203
Course Packet 06

Figure 255: Colors available in TurboC

setbkcolor()

The function that sets the background to the color


specified by color. The argument color can be a name or a
number.
Syntax:
setbkcolor(int color);

setlinestyle()

The function which sets the style for all lines drawn by
line, lineto, rectangle, drawpoly, and so on.
Syntax:
setlinestyle(int linestyle, unsigned upattern, int
thickness);

The linestyle specifies in which of several styles


subsequent lines will be drawn (such as solid, dotted, centered,
dashed). The upattern is a 16-bit pattern that applies only if
linestyle is USERBIT_LINE (4). In that case, whenever a bit in
the pattern word is 1, the corresponding pixel in the line is drawn
in the current drawing color. A value for ‘upattern’ must always
be supplied. It is simply ignored if ‘linestyle’ is not

Course Module: Computer Programming 596


Course
Packet
LM03-EAAC

06 0203

USERBIT_LINE (4). And the thickness specifies whether the


width of subsequent lines drawn will be normal or thick.
Course Packet 06

Table 63. Linestyle Options


Name Value Description Style
SOLID-LINE 0 Solid line ___________
DOTTED_LINE 1 Dotted line ....
CENTER_LINE 2 Centered line _._
DASHED_LINE 3 Dashed line ----------
USERBIT_LINE 4 User-defined line style

setfillstyle()

The function which sets the current fill pattern and fill
color.
Syntax:
setfillstyle(int pattern, int color);

Table 64. Pattern Options


Pattern Value
EMPTY_FILL 0
SOLID_FILL 1
LINE_FILL 2
LTSLASH_FILL 3
SLASH_FILL 4
BKSLASH_FILL 5
LTBKSLASH_FILL 6
HATCH_FILL 7
XHATCH_FILL 8
INTERLEAVE_FILL 9
WIDE_DOT_FILL 10
CLOSE_DOT_FILL 11
USER_FILL 12

settextstyle()

The function which is used to change the way in which


text appears. Using it can modify the size of text, change
direction of text and change the font of text.

Course Module: Computer Programming 597


Course
Packet
LM03-EAAC

06 0203

Syntax:
settextstyle(int font, int direction, int font_size);
Course Packet 06

Table 65. Font Options


Font Value
DEFAULT_FONT 0
TRIPLEX_FONT 1
SMALL_FONT 2
SANS_SERIF_FONT 3
GOTHIC_FONT 4
SCRIPT_FONT 5
SIMPLEX_FONT 6
TRIPLEX_SCR_FONT 7
COMPLEX_FONT 8
EUROPEAN_FONT 9
BOLD_FONT 10

Table 66. Direction Options


Direction Value
HORIZ_DIR 0
VERT_DIR 1

settextjustify()

Text output is justified around the current position (CP)


horizontally and vertically, as specified. The default justification
settings are LEFT_TEXT (for horizontal) and TOP_TEXT (for
vertical). The enumeration text_just in graphics.h provides
names for the horiz and vert settings passed to settextjustify.
Syntax:
settextjustify(int horiz, int vert);

Table 67. Text Justify Options


Name Value Description Action
LEFT_TEXT 0 Horizontal Justify Left-justify text
CENTER_TEXT 1 Horizontal Justify Center text
RIGHT_TEXT 2 Horizontal Justify Right-justify text
BOTTOM_TEXT 0 Vertical Justify Bottom-justify text
CENTER_TEXT 1 Vertical Justify Top-justify text
TOP_TEXT 2 Vertical Justify Left-justify text

Course Module: Computer Programming 598


Course
Packet
LM03-EAAC

06 0203

getmaxx()

The function which returns the maximum X coordinate


Course Packet 06

for current graphics mode and driver.


Syntax:
getmaxx();

getmaxy()

The function which returns the maximum Y coordinate


for current graphics mode and driver.
Syntax:
getmaxy();

getmaxcolor()

The function which returns maximum color value for


current graphics mode and driver. As color numbering starts
from zero, total number of colors available for current graphics
mode and driver are (getmaxcolor()+1).
Syntax:
getmaxcolor();

getx()

The function getx returns the X coordinate of the current


position.
Syntax:
getx();

gety()

The function gety returns the Y coordinate of the current


position.
Syntax:
gety();

Course Module: Computer Programming 599


Course
Packet
LM03-EAAC

06 0203

line()

The function is used to draw a line from a point(x1,y1)


Course Packet 06

to point(x2,y2) i.e. (x1,y1) and (x2,y2) are end points of the line.
Syntax:
line(x1, y1, x2, y2);

lineto()

Function lineto draws a line from the current position


(CP) to the point (x, y), user can get current position using getx
and gety function.
Syntax:
line(x, y);

linerel()

Linerel function draws a line from the current


position(CP) to a point that is a relative distance (x, y) from the
CP, then advances the CP by (x, y). User can use getx and gety
to find the current position.
Syntax:
linerel(x, y);

circle()

The function which draws a circle with center at (x, y)


and given radius.
Syntax:
circle(x, y, radius);

arc()

The function which draws an arc with center at (x, y) and


given radius. start_angle is the starting point of angle and
end_angle is the ending point of angle. The value of angle can
vary from 0 to 360 degree.
Syntax:
arc(int x, int y, int start_angle, int end_angle, int radius);

Course Module: Computer Programming 600


Course
Packet
LM03-EAAC

06 0203

pieslice()

The function pieslice draws and fills a pie slice with


Course Packet 06

center at (x, y) and given radius r. The slice travels from s_angle
to e_angle which are starting and ending angles for the pie slice.
The angles for pie-slice are given in degrees and are measured
counterclockwise.
Syntax:
pieslice(int x, int y, int s_angle, int e_angle, int r);

ellipse()

The function ellipse is used to draw an ellipse (x,y) are


coordinates of center of the ellipse, stangle is the starting angle,
eangle is the ending angle, and fifth and sixth parameters
specifies the X and Y radius of the ellipse. To draw a complete
ellipse starting angle and end angle should be 0 and 360
respectively.
Syntax:
ellipse(x, y, stangle, eangle, xradius, yradius);

fillellipse()

The function which draws and fills an ellipse with center


at (x, y) and (x_radius, y_radius) as x and y radius of ellipse.
Syntax:
fillellipse(int x, int y, int x_radius, int y_radius);

sector()

The function which draws and fills an elliptical pie slice


with (x, y) as center, (s_angle, e_angle) as starting and ending
angle and (x_radius, y_radius) as x and y radius of sector.
Syntax:
sector(int x, int y, int s_angle, int e_angle, int x_radius,
int y_radius);

Course Module: Computer Programming 601


Course
Packet
LM03-EAAC

06 0203

rectangle()

Function rectangle is used to draw a rectangle.


Course Packet 06

Coordinates of left top and right bottom corner are required to


draw the rectangle. left specifies the X-coordinate of top left
corner, top specifies the Y-coordinate of top left corner, right
specifies the X-coordinate of right bottom corner, bottom
specifies the Y-coordinate of right bottom corner.
Syntax:
rectangle(int left, int top, int right, int bottom);

bar()

The function which is used to draw a 2- dimensional,


rectangular filled in bar.
Syntax:
bar(int left, int top, int right, int bottom);

bar3d()

The function which is used to draw a 2-dimensional,


rectangular filled in bar. Coordinates of left top and right bottom
corner of bar are required to draw the bar. depth specifies the
depth of bar in pixels, topflag determines whether a 3-
dimensional top is put on the bar or not (if it is non-zero then it
is put otherwise not).
Syntax:
bar3d(int left, int top, int right, int bottom, int depth, int
topflag);

drawpoly()

The function which is used to draw polygons. num


indicates (n+1) number of points where n is the number of
vertices in a polygon, polypoints points to a sequence of (n*2)
integers. Each pair of integers gives x and y coordinates of a
point on the polygon. User specify (n+1) points as first point
coordinates should be equal to (n+1)th to draw a complete figure
or polygon.

Course Module: Computer Programming 602


Course
Packet
LM03-EAAC

06 0203

Syntax:
drawpoly(int num, int *polypoints );
Course Packet 06

fillpoly()

The function which is used to draw and fill a polygon i.e.


triangle, rectangle, pentagon, hexagon etc. It require the same
arguments as drawpoly().
Syntax:
fillpoly(int num, int *polypoints );

floodfill()

The function is used to fill an enclosed area. Current fill


pattern and fill color is used to fill the area. (x, y) is any point on
the screen if (x,y) lies inside the area then inside will be filled
otherwise outside will be filled, border specifies the color of
boundary of area. To change fill pattern and fill color use
setfillstyle.
Syntax:
floodfill(int x, int y, int border);

outtext()

The function which displays text at current position.


Syntax:
outtext(char *string);

outtextxy()

The function which displays the text or string at a


specified point (x,y) on the screen.
Syntax:
outtextxy(int x, int y, char *string);

getimage()

The getimage function saves a bit image of specified


region into memory, region can be any rectangle. getimage

Course Module: Computer Programming 603


Course
Packet
LM03-EAAC

06 0203

copies an image from screen to memory. Left, top, right, and


bottom define the area of the screen from which the rectangle is
to be copied, bitmap points to the area in memory where the bit
Course Packet 06

image is stored.
Syntax:
getimage(int left, int top, int right, int bottom, void
*bitmap);

putimage()

The putimage function outputs a bit image onto the


screen. putimage puts the bit image previously saved with
getimage back onto the screen, with the upper left corner of the
image placed at (left, top). ptr points to the area in memory
where the source image is stored. The op argument specifies an
operator that controls how the color for each destination pixel on
screen is computed, based on pixel already on screen and the
corresponding source pixel in memory.
Syntax:
putimage(int left, int top, void *ptr, int op);

Course Module: Computer Programming 604


Course
Packet
LM03-EAAC

06 0203

Collaborative Learning Exercise 12


Graphics Manipulation
Collaborative Learning Exercise 12

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with a cover page in our Google Classroom.
Keep your work clean and avoid erasures. Use of pencil is prohibited. Use only blue ballpoint
pen.

Create the program that will produce the figure below. The larger circle should have a diameter
of 80, the smaller circle should have a diameter of 40 and the arc should have a start angle of
269, end angle of 40 and diameter of 88. Use only one command in creating each shape. (25
points)

175,240
420,340
150,250

301,326 Arc: 405,332


300,325

450,400

260,400 350,400

280,410 281,411

Course Module: Computer Programming 605


Course
Packet
LM03-EAAC

06 0203

Laboratory Report 11
Graphics Manipulation
Laboratory Report 11

Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers and post a PDF
File or captured/scanned image of your paper with a cover page in our Google Classroom.
Keep your work clean and avoid erasures. Use of pencil is prohibited. Use only blue ballpoint
pen.

Create a program that will produce the pie chart of the annual work output report of each
employee at the center screen with a diameter of 360, background color 8 and outline and font
color 12. The percentages of the work done by the employees are: Andy 5%, Ben 18%, Catty
7%, Don 15%, Eddy 4%, Frank 15%, Gary 14%, Helen 10%, Ivan 3% and Jack 9%. Draw it in
sequence and use the pattern 11, 9, 5, 7, 10, 2, 8, 3, 6, 4 and color 1, 14, 5, 3, 7, 2, 13, 6, 9, 4
respectively. Print the title EMPLOYEE ANNUAL WORK OUTPUT REPORT at 320, 430
horizontally using size 2 and font face 4 with center justification. Output also the subtitle
BASED ON PERCENTAGES OF TOTAL WORK DONE at 320, 460 with the same settings of
the title. (35 points)

Course Module: Computer Programming 606


Course
Packet
LM03-EAAC

06 0203

Practical Exam 11
Graphics Command
Practical Exam 11

(Topics Covered: All the topics in Course Packet 06 of Learning Module 03)

Remember:
The Practical Exam will be administered face-to-face. You are given an hour to answer this
practical exam. This is an individual assessment, therefore, individual submission of answer to
is required. Cheating in any form is highly discouraged.

Course Module: Computer Programming 607


Course
Packet
LM03-EAAC

06 0203

References
C Tutorial. (n.d.). Retrieved from W3schools.in: https://www.w3schools.in/c-tutorial/intro/
References

C++ Language. (2000). Retrieved June 27, 2016, from cplusplus.com:


http://www.cplusplus.com/doc/tutorial/

Doyle, B. (2014). C# Programming From Problem Analysis to Program Design Fourth Edition. New
Tech Park, Singapore: Cengage Learning Asia Pte Ltd.

Kent, J. (2005). C++ Demystified. USA: Mc Graw Hill Osborne.

Savitch, W. (1996). Problem Solving with C++ The Object of Programming. California, USA:
Addison-Wesley Publishing Company, Inc.

Schildt, H. (1992). Turbo C/C++: The Complete Reference, Second Edition. California, USA:
Osborne Mc-Graw Hill.

Sellappan, P. (2001). C++ Through Examples. Selangor Darul Ehsan, Malaysia: Federal
Publication Sdn. Berhad.

tutorialspoint. (2020). (Tutorials Point (I) Pvt. Ltd.) Retrieved July 3, 2020, from
https://www.tutorialspoint.com/cprogramming/index.htm

Course Module: Computer Programming 608


Course
Packet
LM03-EAAC

06 0203

Learner’s Feedback Form


Learner’s Feedback Form

Name of Student: _____________________________________________________________


Program : _____________________________________________________________
Year Level : ________ Section : _____ Sex at Birth: ___________
Faculty : _____________________________________________________________
Schedule : _____________________________________________________________

Course Packet : Code : _________ Title : __________________________________

How do you feel about the topic or concept presented?


 I completely get it.  I’m struggling.
 I’ve almost got it.  I’m lost.

In what particular portion of this course packet, you feel that you are struggling or lost?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Did you raise your concern to you instructor?  Yes  No

If Yes, what did he/she do to help you?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

If No, state your reason?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

To further improve this course packet, what part do you think should be enhanced?
_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

How do you want it to be enhanced?


_____________________________________________________________________________
_____________________________________________________________________________
__________________________________________________________________________

Course Module: Computer Programming 609


Course
Packet
LM03-EAAC

03 0203

Post-Assessment
Post-Assessment

Computer Programming Using C Language


Name: Score:
Section: Date:
Sex at Birth:
Instructions. Kindly print this out on an A4 bond paper, write your answers in the space
provided and post a captured/scanned image of your paper with a cover page in our Google
Classroom. Erasures and abbreviations mean wrong. Keep your work clean and avoid erasures.
Use of pencil is prohibited. Use only blue ballpoint pen. (20 points)

1. ____________________ is the developer of C Language.


2. ____________________ is used to store many values in a single variable.
3. ____________________ has the scope of a local variable but the lifetime of global variable.
4. ____________________ is used to repeat the process based on the condition set in the
program.
5. ____________________ is the highest and lowest value that a data type can represent.
6. ____________________ is used to terminate the repetition process even when the condition
is true.
7. ______________________________ it combines comparisons in a single if or else if
statement.
8. ____________________ is the error encountered during the execution of a computer
program.
9. ____________________ is a C++ rule for determining which operation is performed first.
10. The conditional operator requires ____________________ operands.
11. ____________________ has the scope of a local variable but the lifetime of a global variable.
12. ____________________ is a way of referring to data and reserving memory necessary to
store that data.
13. ____________________ is the program that translates the C program source code into
machine code.
14. ____________________ is used to delete the graphics design in the output screen.
15. ____________________ has the lowest priority when arithmetic, logical, and relational
operators are combined.
16. ____________________ is a group of statements that together perform a task.
17. ____________________ is a code statement that has a value that needs to be evaluated when
the program runs.
18. Comparison is made using ______________________________.
19. ____________________ is the function used to initializes the graphics systems of TurboC.

Course Module: Computer Programming 610


Course
Packet
LM03-EAAC

03 0203

20. ____________________ is used to manipulate the process by using questions answerable by


true or false inside the program.
Post-Assessment

Course Module: Computer Programming 611


Course
Packet
LM03-EAAC

03 0203

Learner’s Performance Report


Name of Student: _____________________________________________________________
Learner’s Performance Report

Program : _____________________________________________________________
Year Level : ________ Section : _____ Sex at Birth: ___________
Faculty : _____________________________________________________________
Schedule : ____________
_______________________________________________

Learning Module Code Learning Module Title Rating

Course Packet Code Course Packet Title Rating

Course Code: ____________ Title: _________________________________________________

Course Module: Computer Programming 612

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy