0% found this document useful (0 votes)
827 views161 pages

Prog 1 Module

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 161

Republic of the Philippines

POLYTECHNIC UNIVERSITY OF THE PHILIPPINES


OFFICE OF THE VICE PRESIDENT FOR BRANCHES AND CAMPUS
SANTA ROSA CAMPUS
City of Santa Rosa, Laguna

INSTRUCTIONAL MATERIAL FOR


PROGRAMMING 1
(COMP 20023)

BY:

Prof. Eva De Jesus – Villanueva


Faculty
PUP Santa Rosa Campus

June 2020
Table of Contents

UNIT 1 Programming Concepts


1.1 Overview of Hardware, Software & Firmware 1 - 3
1.2 Steps in Program Development 3 - 6

UNIT 2 C Programming Language and Its Structure


2.1 Application of C 9
2.2 Who Uses C? 9
2.3 Basic Structure of C++ Language 10 - 15

UNIT 3 Identifier and Data Type


3.1 Basic Data Type 19 - 20
3.2 Identifiers 21
3.3 Keywords 22
3.4 char and string Data Type 22 - 23

UNIT 4 Declaring Variables and Constants


4.1 Variables in C++ 25 - 28
4.1.1 Global and Local Variables 29
4.2 Constant in C++ 29 - 30

UNIT 5 Operators
5.1 Assignment Operators 32 - 33
5.2 Arithmetic Operators 33
5.3 Increment and Decrement Operators 34
5.4 Relational or Comparison Operators 34 - 35
5.5 Logical Operators 35 - 36
5.6 Operator Precedence 36 - 37

UNIT 6 Comments
6.1 Types of C++ Comments 40 - 41
6.2 Using comments When Debugging 41

UNIT 7 Output Statement


7.1 cout statement 43 - 47
7.2 Using endl and \n with cout 47 - 48
7.3 Escape Sequences 48 - 50
UNIT 8 Input Statement
8.1 cin statement 52 - 56
8.2 How to input string? 56 - 61

UNIT 9 Conditional Statement


9.1 if statement 64
9.2 if else statement 65 - 66
9.3 if else if statement 67 - 68
9.4 Nested if statement 69 - 71
9.5 switch statement 71 - 73
9.6 Nested switch statement 74 - 75

UNIT 10 Looping - for statement


10.1 for statement 80 - 82
10.2 Nested for loop statement 82 - 84
10.3 Infinite loop 84 - 86

UNIT 11 Looping - while and do…while statement


11.1 while and do…while statement 89 - 93
11.2 Nested while and do…while statement 94 - 95

UNIT 12 Array
12.1 Array 100 -101
12.2 Array Declaration and Initialization 101 -102
12.3 Assigning Values to an Array 102 - 103
12.4 Asking the User to Enter Size of Array 103
12.5 Getting the Sum and Average of an Array 103 -104
12.6 Finding the Largest and Smallest Value 104
12.7 Counting 105
12.8 Searching an Array 105
12.9 Sorting an Array 105 - 106

UNIT 13 Functions
13.1 Function Declaration and Function Calling 112 - 113
13.2 Function Prototype 114
13.3 Types of User-Defined Function 115 - 119
13.4 Function Calling another Function 119 - 120
13.5 Passing Array the Function 121 - 122
13.6 Recursive Function 123 - 125
13.7 C++ Mathematical Function 126 - 128
UNIT 14 String Manipulation
14.1 C-Style String and String Class 132 - 133
14.2 Declaration and Initialization of String 133
14.3 Assignment Operator 134
14.4 Other String Functions 134 - 142

UNIT 15 Pointers

15.1 Pointer Declaration 146


15.2 Reference and Dereference Operators 146 -147
15.3 Pointers in C++ 148 -152
Programming Concepts

UNIT 1: Programming Concepts

Introduction

Programming is the act of writing codes or instructions for the computer to execute. We
write programs because we would like the computer to solve a specific problem. Programs more
often than not are complex. A system (ex. Payroll system) is not only one program, but it is a
consolidation of several programs working together. For this reason, a system is developed by
several programmers and analyst.

There are several computer languages that are available to write programs. The choice
depends on the type of system or application you will develop or it can be based on the current
system your client is using. Studying computer languages will only be hard and confusing at the
beginning but once you become familiar with one and use it to write codes it will be easier for
you to study on your own other computer languages.

The tool that we use to write program is a computer. Sometimes, when we hear the word
computer, we imagine a keyboard, a monitor, a mouse and a CPU box or sometimes a laptop.
But nowadays, computer can take many form, it can also be a tablet or a smart phone. Your
regular android phone can be used to write programs. Example, there are compilers for C++
that you can download for free on your phone and write programs from there. Of course, it is not
allowed to use your phone to write programs for work, but for this class you can, especially
when you don’t have a laptop or pc at home. Smart phones are also portable but the size of the
screen is small and it is hard to type long programs with a small keypad.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Differentiate hardware, software and firmware.


2. Identify different types of computer.
3. Enumerate and explain the steps in program development
4. Analyze programming problems

1
Programming Concepts

Course Materials

1.1 Overview of Hardware, Software and Firmware

A computer is

- an electronic device
- that you feed with data and instructions (program),
- process data based on instructions given,
- stores data and result of processing (information) and
- display information needed or requested by the authorized user

Some computers can perform several task (general-purpose computers) like you can use it
to type documents, browse the Internet, watch movie, play games etc. it really depends on what
software or programs are installed in your computer, others are dedicated to perform one
specific task (special-purpose computer).

Computer can take many forms, they can be:

- desktop computer
- laptop
- tablet
- servers
- smart phones
- game consoles
- wearables
- smart TVs
- …

The physical part of the computer is what we call the hardware and the programs that we
install or use to run the computer and process our data is the software. The programs that are
part of the hardware or the programs that were installed in the hardware while it is being
manufactured is the firmware. When we buy a laptop or pc or any computer a program is
already installed in it, we cannot erase or modify them anymore, this program starts-up our
computer they look for the Operating System installed in our hard disk and load it to the memory
of the computer.

Hardware device can be classified as:

- Input device – to receive data and information

- Output device - to disseminate information ( result of processing)

- Storage device – save data or information for future use

- Processing device – transforms our data into information based on the program we have

2
Programming Concepts

There are many classifications of software but for me, they fall in these two categories.

- System Software – these are the programs that control our hardware – the different
devices and how they can get connected to other devices and network.

- Application Software – these are programs that are specialized or customized for a
particular group of users. They can be readily available (you can buy them online or in
special computer shops) other needs to be developed or customized for particular user
(a company or agency) only.

Freeware are two words – free and software, they are software that you can
download or copy at no cost..

1.2 Steps in Program Development

Developing a program is comparable to building your dream house. It should be


carefully planned, checked and maintained. Sometimes, we make some modification or
renovations depending on the needs of the users or when new regulations (ex. tax law/rates)
arise. The steps in program development are:

1. Problem Definition
2. Program Design
3. Coding and Debugging
4. Testing
5. Documentation
6. Maintenance

Problem Definition – it is the careful understanding and identification of the problem why a
program needs to be written or develop. This is the most crucial step because if we fail to
identify the real problem a concrete and reliable solution/program cannot be developed. The
program may not have any error but it will not serve the real purpose why we develop it.

Here, we should identify the following: required outputs, the input data available and
where we can get them, the processing procedures, memory requirements, error handling and
the interface with other system of program must be identified and taken into consideration.

We just don’t sit down in front of our computer and write codes immediately. Like in
building our dream house, before the architect can draw the design, the owner already decided
– how many floors, bedrooms, toilet, etc. then the architect or the engineer will start working on
those ideas plus other inputs like the location and size of lot, the regulations of the subdivision
and municipality. You can also tell the architect that you have plans of adding a room, a pool or
anything in the future.

3
Programming Concepts

Program Design – the program developer makes use of several tools to develop the design of
the program like a flowchart or an algorithm. This is like having a house plan drawn and signed
by architects and several engineers.

Flowchart – is the graphical representations of the steps on how to solve a particular


programming problem. It uses several symbols connected by lines to show the flow or sequence
of the solution.

Symbols Used In Flowchart

Symbol Purpose Description

Indicates the flow of logic by connecting


Flow line
symbols.

Terminal(Stop/Start) Represents the start and the end of a flowchart.

Input/Output Used for input and output operation.

Used for arithmetic operations and data-


Processing
manipulations.

Used for decision making between two or more


Decision
alternatives.

On-page Connector Used to join different flowline

Used to connect the flowchart portion on a


Off-page Connector
different page.

Predefined Represents a group of statements performing


Process/Function one processing task.

https://www.programiz.com/article/flowchart-programming

4
Programming Concepts

Find the largest among three different numbers entered by the user.

Flowchart to find the largest among three numbers.


https://www.programiz.com/article/flowchart-programming

Drawing flowchart can be useful in analyzing a problem that can help you in writing your
codes but if the program is too complex and big, drawing the flowchart can be more tedious
than writing the actual program. If this will be the case, you can write an algorithm for your
program design.

Algorithm – is a step-by-step solution to a problem written in simple English or in the


language spoken by the programmer. These steps will set as a guide in writing the computer
codes.

Algorithm of linear search :


1. Start from the leftmost element of arr[] and one by one compare x with
each element of arr[].
2. If x matches with an element, return the index.
3. If x doesn’t match with any of elements, return -1.
Here, we can see how the steps of a linear search program are explained in a simple, English
language.
https://www.geeksforgeeks.org/difference-between-algorithm-pseudocode-and-program/

5
Programming Concepts

Coding and Debugging – this is where the actual computer program is written or entered in the
computer using the chosen computer language (coding) and some minor errors are eliminated
and corrected (debugging).

An error that is detected by the compiler is what we call syntax error like a misspelled
word, missing punctuation, a bracket or brace with no pair. It is an error in the format of using an
statement or command of the language. Another error which is cannot be detected by the
compiler and hard to detect is the logical error. Logical errors are executed unlike when the
compiler encounters syntax errors the program will not execute and the compiler will make a list
of all the syntax errors it encountered.

Example: Compute the average of three numbers and store them in variable X

X=7+5+6/3; this line will be executed but the answer is wrong, the compiler will
not tell you to put a parenthesis around the 7 + 5 + 6. (logical error)

X = (7 + 5 + 6) / 3 the formula is correct but you forgot to put a semicolon at the end.
This time the compiler will tell you that a ; is expected. (syntax error)

Testing – the program is tested using all possible data that it might encounter to ensure the
quality of its output. The test plan is usually part of the program design. Before implementing
the new program or system it should first run alongside with the old system to see if they will
produce the same result. Some systems/programs are replaced because of new technologies
or it might need to connect to other system that the old one cannot do.

Documentation - this is a very essential part of program development that sometimes taken
lightly specially if project is small and not really formalize. Documentation helps the users on
how to use the program and how to maintain the software. Programmers will have a hard time in
revising or maintaining the program if there are no documentations or manuals most specially, if
it is written by another programmer who may not be around anymore to clarify some of your
concerns.

All appliances or gadgets that we bought come with a manual that will tell us how to
assemble or use them. So, programs or systems developed must also come with their own
manual or documentation to guide its new user (ex. how to install, memory requirements, type
of monitor, size of printer, etc.)

Maintenance – is done after your program or system is turn over to the actual user. Updating is
done or new codes are added or deleted if new specifications arise or the user will use another
set of equipments. Other times, errors are encountered and the developer or programmer will
be called to correct the program or parts of it.

6
Programming Concepts

Activities

1. Make a diagram to highlight the steps in program development.


2. Make a collage for the different input and output device.
3. Continue my analogy in the steps in program development (comparing it to building your
dream house).

Online References

https://edu.gcfglobal.org/en/computerbasics/what-is-a-computer/1/

https://www.geeksforgeeks.org/software-engineering-program-development-life-cycle-pdlc/

https://study.com/academy/lesson/what-is-an-algorithm-in-programming-definition-examples-
analysis.html

7
C Programming Language and Its Structure

UNIT 2: C Programming Language and Its Structure

Introduction

C is a general-purpose and procedural programming language. It was initially developed


by Dennis Ritchie in the year 1972 at the Bell Telephone Laboratories. It was mainly developed
as a system programming language to write an operating system (UNIX OS). C language is still
one of the most popular and most widely used among computer programming languages.
Among the reasons why C is popular are: it is machine-independent, easy to learn, can handle
low-level activities and produces efficient programs. It is a must for students and software
professionals to learn C programming if they want to develop other systems software.

Because of its simplicity and good features, many languages that were developed after C
have borrowed its syntax and features directly or indirectly. Like syntax of Java, PHP,
JavaScript, and many other languages are mainly based on C language.

C++ is an improved version of C language. It has additional features such as type


checking, object-oriented programming, exception handling etc. It was developed by Bjarne
Stroustrup starting in 1979 at Bell Labs.

C++ runs on a variety of platforms, such as Windows, Mac OS, and the various versions
of UNIX. C++ was originally known as “C with classes” and was renamed C++ in 1983. It has
now different versions.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. State some of the uses of C programming language.


2. Identify the basic parts of the program written in C++.
3. Describe the function of each part of the program structure.
4. Write, compile and run your first program.

8
C Programming Language and Its Structure

Course Materials

2.1 Applications of C
C was intended for system development work, particularly the programs for operating
system. C was adopted as a system development language because it produces codes that
are comparable to codes written in assembly language in terms on how fast they run/execute.
Also, the format and syntax of C is much easier to understand than in Assembly. Some
examples of the use of C are:
 Assemblers
 Databases
 Language Compilers
 Language Interpreters
 Modern Programs
 Network Drivers
 Operating Systems
 Print Spoolers
 Text Editors
 Utilities

2.2 Who uses C++? https://www.guru99.com/cpp-tutorial.html#3

Some of today's most visible used systems have their critical parts written in C++.

Examples are Amadeus (airline ticketing)

 Bloomberg (financial formation),


 Amazon (Web commerce), Google (Web search)
 Facebook (social media)

Many programming languages depend on C++'s performance and reliability in their


implementation. Examples include:

 Java Virtual Machines


 JavaScript interpreters (e.g., Google's V8)
 Browsers (e.g., Internet Explorer, Mozilla's Firefox, Apple's Safari, and Google's
Chrome)
 Application and Web frameworks (e.g., Microsoft's .NET Web services framework).

Applications that involve local and wide area networks, user interaction, numeric, graphics, and
database access highly depend on C++ language.

9
C Programming Language and Its Structure

2.3 Basic Structure of C++ Language

A program is composed of sequence of statements or instructions. You use a text editor


to type/encode your program and then save it on your storage medium, this is now your source
code. C++ is a compiled language. The source code is compiled into object files. Object files
are then combined by a linker creating an executable program.

Consider the famous “Hello World!” program of C language, and let’s examine every line
of it.

1 // my first C++ program


2
3 #include<iostream>
4
5 using namespace std;
6
7 int main()
8 {
9 cout << "Hello World!" << endl;
10 return 0;
11 }

C++ program structure is divided into various sections, namely:

1. headers,
2. class definition,
3. member functions definitions and
4. main function.

Note that in C++, a program can be written with or without a class and its member
functions definitions. A simple C++ program (without a class) includes comments, headers,
namespace, main() and input/output statements.

Let us now examine our Hello World program.

Line 1 is a comment line. Comments are important element of a program that is used to
increase the readability of a program and to describe its function. Comments are not executable
statements so they are ignored by the compiler. There are two ways to write comments. It can
be written with double slash at the beginning (//) for single-line comment or can be enclosed
within /* and */ for multi-line comments.

10
C Programming Language and Its Structure

Line 2, 4 and 6 Whitespace is a term that refers to characters that are used for formatting
purposes. In C++, this refers primarily to spaces, tabs, and newlines. The C++ compiler
generally ignores whitespace, with a few minor exceptions (when processing text literals or
when they are inside “ “ ). We use whitespace to make our program easier to read.

Examples:

Although both are correct, cout << “Hello World!”; is better than cout<<”Hello World!”;

a=b+c/d; is harder to read than a = b + c / d;

int main(){ looks cramp without proper indention


cout << "Hello World!"<<endl; and spacing
return 0;
}

cout << "Hello world!\n"; // cout resides in the iostream library


cout << "It is my first time here.\n"; // these comments make the code hard to read
cout << "Cheers!\n"; // especially when lines are different lengths

is more readable than

cout << "Hello world!\n"; // cout resides in the iostream library


cout << "It is my first time here.\n"; // these comments make the code hard to read
cout << "Cheers!\n"; // especially when lines are different lengths

Line 3 #include <iostream>. It instructs the compiler to include the standard stream I/O library.
Without this header inclusion, the expression cout << “Hello World!”; would not compile

A program includes various elements like built-in functions, classes, keywords,


constants, operators, etc., that are already defined in the standard C++ library. In order to
use such pre-defined elements in a program, an appropriate header must be included in
the program. The standard headers contain the information like prototype, definition and
return type of library functions, data type of constants, etc. As a result, programmers do
not need to explicitly declare (or define) the predefined programming elements.
Standard headers are specified in a program through the preprocessor directive
#include. In our program, the iostream header is used. When the compiler processes the
instruction #include<iostream>, it includes the contents of iostream in the program. This
enables the programmer to use standard input, output and error facilities that are
provided only through the standard streams defined in <iostream>.

https://ecomputernotes.com/cpp/introduction-to-oop/structure-of-a-cpp

11
C Programming Language and Its Structure

Line 5: using namespace std;

Since its creation, C++ has gone through many changes by the C++ Standards Committee.
One of the new features added to this language is namespace. A namespace permits
grouping of various entities like classes, objects, functions and various C++ tokens, etc.,
under a single name. Different users can create separate namespaces and thus can use
similar names of the entities. This avoids compile-time error that may exist due to identical-
name conflicts.
The C++ Standards Committee has rearranged the entities of the standard library under a
namespace called std. In Figure, the statement using namespace std informs the compiler
to include all the entities present in the namespace std. The entities of a namespace can be
accessed in different ways which are listed here.
• By specifying the using directive using namespace std;
cout<<"Hello World";

• By specifying the full member name std: :cout<<"Hello World";

• By specifying the using declaration using std:: cout;


cout<<"Hello World";
As soon as the new-style header is included, its contents are included in the std
namespace. Thus, all the modern C++ compilers support these statements:
#include<iostream>
using namespace std;
However, some old compilers may not support these statements. In that case, the
statements are replaced by this single statement.
#include<iostream.h>

https://ecomputernotes.com/cpp/introduction-to-oop/structure-of-a-cpp

Line 7 int main().This is the main function of the program. Functions are denoted by the
parentheses(). Before the main function is "int". This means that the main function will return an
integer to the function or process that called it. A program can have many function but only the
main() is executed automatically, others need to be called to be run.

Line 8 and 11 Curly braces, { }, express grouping in C++. Here, they indicate the start and end
of the function body. We prefer the opening brace and the closing brace appear on their own line
and indented on the same level. If you get a compile error of missing { or missing } it will be easy to
find the one with the missing pair.

12
C Programming Language and Its Structure

Example:

Below matching {} are aligned,

int main()
{
for ( ; ; )
{
statement;
if ( condition)
{
statement;
}
else
{
statement;
}
statement;
}
}

Compared to:

int main() {

for ( ; ; ){
statement;
if ( condition) {
statement;
}
else {
statement;
}
statement;
}
}

It is hard to look for the matching {}.

13
C Programming Language and Its Structure

Line 9: cout << “Hello World!” << endl;

This line displays Hello World! on your computer screen. We use cout << if we want to
display something on the screen. Whatever is inside the double quotation marks are displayed.
If not surrounded by “ “, like cout << tax; the compiler will treat tax as a variable that holds a
certain value and that value will be displayed on the screen. C++ statement ends with a
semicolon.

endl is like moving the cursor to the next line. So, if we issue:

cout << “Hello World!” << endl;


cout << “Here in Laguna.”;

output will be:

Hello World!
Here in Laguna.

cout << “Hello World!”;


cout << “Here in Laguna.”;

output will be:

Hello World!Here in Laguna.

Spaces within the double quotation marks are counted and displayed.

cout << “Hello World!” << endl;

will give a different output form

cout << “Hello World!” << endl;

output:

Hello World!
Hello World!

Line 10 return 0; This is the last command in the main function. Its purpose is only to return a
value to the function or process that called the main function. It is required by the "int" in front of
the main function definition. It should return a zero from the main function meaning the program
ran successfully and exited.

14
C Programming Language and Its Structure

Here is another example program,

1 // program that adds two integer values


2
3 #include<iostream>
4
5 using namespace std;
6
7 int main()
8 {
9 int a = 8;
10 int b = 10;
11 cout << "The sum of " << a << " + " << b << " is " << a+b;
12 return 0;
13 }

Ouput:
The sum of 8 + 10 is 18

Line 9 and 10 declare a and b as storage for values 8 and 10 respectively. int means that they
will store an integer value or whole numbers.

Line 11 cout << "The sum of " << a << " + " << b << " is " << a+b;

Will display on your screen what’s inside the “ “ and the value represented by a and b (notice
they are not enclosed with double quotes) and the answer to the direct computation a+b.

We can declare another variable, c to hold the answer for a + b and substitute it to a+b in cout.

1 // program that adds two integer values


2
3 #include<iostream>
4
5 using namespace std;
6
7 int main()
8 {
9 int a = 8;
10 int b = 10;
11 int c = 0;
12 c = a + b;
13 cout << "The sum of " << a << " + " << b << " is " << c;
14 return 0;
15 }

15
C Programming Language and Its Structure

Activities

A. Answer the following:

1. What are the reasons why C language is still popular today?


2. Give examples of other software or applications not mention in this module that is written
using C or C++.
3. Enumerate the various sections of a C++ program.
4. What is wrong with the following program?

// program that converts inches to centimeter

#include<iosteam>

using namespace std;

int main()
{
int inches = 15;

cout << "The equivalent of " << inches << inches in centimeter is " << b << inches * 2.45;

return 0;
}

5. Write a program the will compute the number of churchgoers that will be allowed to
attend the mass if only 50% of the total capacity is mandated. Use:

int totalCapacity =325;

B. Read the following:

1. history of C++ in https://www.geeksforgeeks.org/history-of-c/


2. Why do we need using namespace std; https://medium.com/breaktheloop/why-
using-namespace-std-is-used-after-including-iostream-dc5ae45db652
3. Applications of C++ https://www.mycplus.com/featured-articles/top-10-applications-
written-in-c-cplusplus/

C. Install C++ compiler in your pc, laptop or smart phone. Steps on how to install are
available online.

16
C Programming Language and Its Structure

Online References

https://www.guru99.com/cpp-tutorial.html#3

https://ecomputernotes.com/cpp/

https://www.geeksforgeeks.org/history/

17
Data Types and Identifiers

UNIT 3: DATA TYPES AND IDENTIFIERS

Introduction

A program is normally written to process data or information. To manage these data a


program must identify data according to their type. Some data can be:

 numeric (whole number or with fractional part),


 alphabetic (in uppercase A-Z, or in lowercase a-z),
 special character ( ex. !”#$%&’()?= ), or
 combinations of digits, alphabetic and special characters

Data or information is placed in the memory of computer while the program is executing.
Imagine the memory of computer as a big storage with many shelves. Each shelf can only hold
one piece of data. To be able to access these data, each shelf containing a piece of data should
be named in order to be identified. Data are placed anywhere in the memory of your computer.
The size of memory allocated for each data depends on its type. For now, you don’t need to
know where they are located or to know their exact address to be able to run your program.

50 2020

age cYear

1970

bYear

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Identify the basic types of data.


2. Create appropriate identifier / name to hold data based on the rules of C++ language.
3. Identify C++ keywords that cannot be use as an identifier.

18
Data Types and Identifiers

Course Materials

3.1 Basic Data Types

The data type specifies the size and type of information the variable can store:

Data Size Description


Type

int 4 bytes Stores whole numbers, without decimals

float 4 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 7 decimal digits

double 8 bytes Stores fractional numbers, containing one or more decimals. Sufficient for
storing 15 decimal digits

boolean 1 byte Stores true or false values

char 1 byte Stores a single character/letter/number, or ASCII values

https://www.geeksforgeeks.org/c-data-types/

Data type modifiers available in C++ are:


 Signed
 Unsigned
 Short
 Long

It is written before the data type to widen or shorten the range of values it can represent. If
data type is written without the modifiers it will use the default range.

19
Data Types and Identifiers

The table summarizes the modified size and range of built-in data types when combined
with the type modifiers:

DATA TYPE SIZE (IN BYTES) RANGE

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

unsigned int 4 0 to 4,294,967,295

Int 4 -2,147,483,648 to 2,147,483,647

long int 4 -2,147,483,648 to 2,147,483,647

unsigned long int 4 0 to 4,294,967,295

long long int 8 -(2^63) to (2^63)-1

unsigned long long int 8 0 to 18,446,744,073,709,551,615

signed char 1 -128 to 127

unsigned char 1 0 to 255

Float 4

Double 8

long double 12

wchar_t 2 or 4 1 wide character


https://www.geeksforgeeks.org/c-data-types/

Note : Above values may vary from compiler to compiler. In above example, we have
considered GCC 64 bit.

In declaring data type, make sure that it will suit the kind of data you will process. For
example, if your data is

 population use unsigned int


 price of an item use float
 name of a person use string
 middle initial use char
 phone number use string since it will not be used for computation

20
Data Types and Identifiers

3.2 Identifier

The C++ identifier is a name given to identify a variable, function, class, module, or any
other user-defined item. An identifier always starts with a letter A to Z or a to z or an underscore
(_) followed by zero or more letters, underscores, and digits (0 to 9).
C++ does not allow punctuation characters such as @, $, and % within identifiers. C++ is a
case-sensitive programming language. Thus, grossPay and GrossPay are two different
identifiers in C++.
In giving names, make sure that it somehow describes the data that it holds or the purpose
of the function or module. Appropriate identifiers can help programmers in debugging program,
especially if they are not the ones who wrote it.

Examples of good identifiers:


 grossPay
 gross_pay
 midtermGrade
 customerName
 VAT
 Quarter3

Examples of bad identifiers


 X
 Gp
 Mg
 Cn
 Q3

You can easily forget what kind of data a variable holds if you use initials as identifiers.

Note: To make your identifier easier to read you can use an underscore ( _ )in between
two words (i.e. net_pay) or you can capitalize the beginning of succeeding words (i.e.
finalGrade, firstQuarterSales, cityPopulation). C++ keywords are reserved words and
cannot be used as an identifier.

21
Data Types and Identifiers

3.3 C++ Keywords


The following list shows the reserved words in C++. These reserved words may not be
used as constant or variable or any other identifier names.

asm else new this

auto enum operator throw

bool explicit private true

break export protected try

case extern public typedef

catch false register typeid

char float reinterpret_cast typename

class for return union

const friend short unsigned

const_cast goto signed using

continue if sizeof virtual

default inline static void

delete int static_cast volatile

do long struct wchar_t

double mutable switch while

dynamic_cast namespace template

https://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm

char and string data type

Values declared as char must be enclosed with a single quotation mark.

Examples: ‘s’, ‘3’, ‘ ‘, ‘$’

String data type is actually an array of characters. In the earlier version of C language,
there is no string data type, so if data is more than one character you need to declare it as an
array of characters.

22
Data Types and Identifiers

Example:

In older version, you need to specify the maximum length of the variable, like:

char schoolName[100] = {‘ ‘};

// with this declaration schoolName is limited only to 100 characters

cin >> schoolName;

P o l y t e … \0
n
0 1 2 3 4 5 41 95 96 97 98 99

‘\n’ character specify the end of the string

cout << schoolName.length(); 41

cout << schoolName[0]; P

cout << schoolName[7]; h

cout << schoolName[40]; s

With the new version of C language, you can now use the string data type.
They are enclosed with double quotation marks ( “ “).

string schoolName = “ “;

How many characters can a string hold?

size_type string::max_size() const

 Returns the maximum number of characters that a string is allowed to


have.
 This value will vary depending on operating system and system
architecture.

Sample code:

1 string sString("MyString");
2 cout << sString.max_size() << endl;

Output:

4294967294

https://www.learncpp.com/cpp-tutorial/17-3-stdstring-length-and-capacity/

23
Data Types and Identifiers

Activities

Write appropriate identifier and data type to represent the following data:

Data Type Identifier

1. Name of hospital ______________ _________________


2. Discounted price ______________ _________________
3. Number of attendees in a meeting ______________ _________________
4. Letter grade ______________ _________________
5. Weekly pay ______________ _________________
6. Hourly rate ______________ _________________
7. Gender ______________ _________________
8. Speed of car in kph ______________ _________________
9. Size of room in sqm ______________ _________________
10. Mobile number ______________ _________________

Online References

https://www.geeksforgeeks.org/c-data-types/

https://www.learncpp.com/cpp-tutorial

https://www.tutorialspoint.com/cplusplus/cpp

24
Variables and Constants

UNIT 4: DECLARING VARIABLES AND CONSTANTS

Introduction

Variables are values that can change during the program execution. The values can be
given by the programmer who wrote the program, it can also be the result of a computation or
the user of the program can be asked to enter its value.

Constants are values that are declared at the beginning of the program. It is fixed and
you cannot change the value during the program execution. For example, VAT (value-added
tax) is 12%, so at the beginning of the program you can declare VAT as constant with the value
of 0.12. If there will be computation in the program using VAT, you just use VAT and not 0.12. If
the BIR change the value of VAT to 15%, all you need to change is 0.12 to 0.15 in the constant
declaration. You don’t need to scan the program to look for all 0.12 and change them to 0.15.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Recognize if data is a variable or a constant.


2. Declare variables and constants as needed.
3. Give appropriate variable and constant names based on the rules in naming
Identifiers.
4. Determine when to declare global or local variable or constant.

Course Materials

4.1 Variables in C++

A variable is a name given to a memory location that stores your data.

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In C++, all the variables must be declared before use.
 It is case-sensitive.

How to declare a variable?

 data_type variable_name;
 data_type variable_name = value;

25
Variables and Constants

 data_type variable_name1, variable_name2, variable_name3;

data_type: Type of data that can be stored in this variable.


variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

Variables must be declared before use, but normally, they are declared at the
beginning of the program.

Examples:

 string stud_name = “Juan dela Cruz”;


 string cust=name = “ “;
 int age = 0;
 float hourlyRate = 190.75;
 string mobileNo =”09xxxxxxxxx”
 char status = ‘S’ ;
 char civil_status = ‘ ‘ ;

You can also declare multiple variables of the same type at the same time.

 float midGrade, finalGrade;


 gloat midGrade =0.0, finalGrade =0.0;

It is a good programming habit to always initialize or give initial value to the variables that
you declare so it will not pick up the previous value of the memory location your variable was
assigned to. Not giving initial value might affect the result of the computation. Also bear in mind
that string is enclosed with double quotation marks and character with single quotation mark.

In the program below, you normally expect that the value of all the variables will be zero
but look at the output.

#include <iostream>
using namespace std;
int main ()
{
float grade1, grade2, grade3;

cout << grade1 << endl;


cout << grade2 << endl;
cout << grade3 << endl;

return 0;
}

26
Variables and Constants

In the next example only the variable grade3 is initialized as 0.0. So grade1 and grade2
may have another initial value.

#include <iostream>
using namespace std;
int main ()
{
float grade1, grade2, grade3=0.0;

cout << grade1 << endl;


cout << grade2 << endl;
cout << grade3 << endl;

return 0;
}

27
Variables and Constants

The best way is to initialize all the variables that you declare, usually to zero if it numeric
or null/blank value if declared as character or string..

The example below shows how to initialize multiple variables declared with a same data
type.

#include <iostream>
using namespace std;
int main ()
{
float grade1=0.0, grade2=0.0, grade3=0.0;

cout << grade1 << endl;


cout << grade2 << endl;
cout << grade3 << endl;

return 0;
}

float grade1=0.0, grade2=0.0, grade3=0.0;

is the same with

float grade1=0.0;
float grade2=0.0;
float grade3=0.0;

28
Variables and Constants

4.1.1 Global and Local Variables

Variables and constants are usually declared as local. How will you know if it is local or
global and what is the effect of declaring such. Global variables and constants are declared
before int main()or outside of any user-defined function. Values stored in global variables
and constants can be accessed and can be changed by other functions aside from main()
function. We learned in the previous lesson that your program can be composed of several
functions but the main() function is the first function that is executed, then you can call other
functions from there.

Local variables and constants are declared inside the function. You can only use them
inside the function where they are declared. When you exit that function, the value of the local
variables are also gone. In our future lessons, I will show you how you can pass the value of a
local variable to other function. For now, let us use main() function.

#include<iostream>
using namespace std;

int currentYear = 2020; // this is a global variable

int main()
{
int birthYear = 0; // this is a local varibale
:

4.2 Constant in C++

Constants are values that do not change from the time you declare them until you exit the
program. You can give name to a constant value and declare it before or inside a function.

There are two ways to declare constant:

1. Using #define preprocessor directive


2. Using a const keyword

Using #define preprocessor directive: This directive is used to declare an alias name
for existing variable or any value. We can use this to declare a constant as shown below:

# constantName value

 constantName: It is the name given to constant.


 value: This refers to any value assigned to constantName.

29
Variables and Constants

#include<iostream>
using namespace std;

#define currentYear 2020 // this is a global constant

int main()
{
int birthYear = 0; // this is a local variable
int age = 0;

Notice that there is no semicolon at the end of #define currentYear 2020 and no
equal sign between currentYear and 2020.

Using a const keyword: Using const keyword to define constants is as simple as defining
variables, the difference is you will have to precede the definition with a const keyword.

const data_type constantName = value;

#include<iostream>
using namespace std;

int main()
{
const int currentYear = 2020; // this is a local constant

int birthYear = 0; // this is a local variable


int age = 0;

Note: If you declare it before main() function it is global. If you want to use the value for
a specific function then declare it inside that function.

There will also be an error if you try to change the value of a constant.

Ex. currentYear = currentYear+5;

or

currentYear = 2021;

The error will be assignment of read-only variable ‘currentYear’

30
Variables and Constants

Activities

Declare and initialize a C++ variable or constant that is appropriate for the following
data. Follow the rules in giving variable name in C++.

1. monthly consumption of electricity in kwh of one family


__________________________________
2. inflation rate for the month of July
___________________________________________________
3. name of a beauty pageant candidate
___________________________________________
4. letter grade of a student
__________________________________________________________
5. total population of the Philippines
___________________________________________________
6. integer called sum and initialize it to 10
___________________________________________________
7. the name of the course of a student.
___________________________________________________
8. multiple integer variables sum, age, and section to 0.
___________________________________________________
9. Declare DiscRate as constant with the value of 0.15
___________________________________________________
10. Declare schoolName as a constant with the value “Polytechnic University of the
Philippines”
___________________________________________________

Online References

https://www.programiz.com/cpp-programming/variables-literals

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

https://www.geeksforgeeks.org/different-ways-declare-variable-constant-c-c/

31
Operators

UNIT 5: OPERATORS

Introduction

Operators are special symbols use to perform operations on variables and constant
values. For example, a plus sign ( + ) is used for adding values. Operators can be used along
with some variables and constant. Since, almost all computer programs perform calculations it
is important to know how to make the right formulas with the use of operators available in C++
and their precedence.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Identify the different types of operators.


2. Explain the function of each operator.
3. Explain the precedence of operators or the hierarchy in evaluating operations or
formulas.
4. Construct formulas using the different operators

Course Materials

Now that we know what are variables and constants, we can begin doing some operations
with them with the use of operators.

C++ commonly used operators are the following:

 Assignment operators
 Arithmetic operators
 Comparison operators
 Logical operators

5.1 Assignment Operator ( = )

The equal sign ( = ) is used to assign a value to a receiving variable. It stores the result of
the operation on the right side of the equal sign.

Examples

minFare = 9.00; // assigns or stores 9.00 to variable minFare

32
Operators

grabFareRate = taxiFareRate; // grabFareRate will be the same with the value of

taxiFareRate

dollar2peso = amtDollars * 51.75; // operations can be a combination of variables,

constants and some operators

Note: The format is: receivingVariable = operations;


If you typed, amtDollars * 51.75 = dollar2peso your program will produce an error.

Compound Assignment Operators ( += , - = , * = , /= , %= )

Expression Equivalent to …
a += b; a = a + b;
x -= 10; x = x – 10;
c *= m; c = c * m;
y /= 5; y = y / 5;
d %= 3; d = d % 3;
m *= a + 5; m = m * (a + 5);

5.2 Arithmetic Operators ( +, -, *, /, %)

Arithmetic operators are used to perform common mathematical operations.

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo

The last one, modulo operator, represented by a percentage sign (%), gives the remainder
of a division of two values. For example:

x = 15 % 2;

results in variable x containing the value 1, since dividing 15 by 2 is equal to 7, with a remainder
of 1

33
Operators

5.3 Increment and Decrement Operators ( ++, --)

The increment operator (++) and the decrement operator (--) increase or reduce by one
the value stored in a variable. They are equivalent to +=1 and to -=1, respectively. Thus:

++x; x+=1; and x = x + 1;

are all equivalent in its functionality; the three of them increase by one the value of x.

It can be used both as a prefix and as a suffix. That means that it can be written either
before the variable name (++x) or after it (x++). This will have an effect if used with other
variables, constants or operators.

Examples:

a = 5; a = 5;
b = a++; b = ++a;

is equivalent to: is equivalent to:

a =5; a = 5;
b = a; a = a + 1;
a = a + 1; b = a;

// b will be equal 5 // b will be equal 6


// a will be equal 6 // a will be equal 6

5.4 Relational or Comparison Operators (==, !=, >, <, >=, <=)

Relational operators are used to compare two values. The return value of a comparison is
either true (1) or false (0).

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

Examples:

(8 == 5) // evaluates to false
(5 > 3) // evaluates to true
(3 != 9) // evaluates to true

34
Operators

(5 >= 5) // evaluates to true


(6 < 6) // evaluates to false

Suppose that a=3, b=2 and c=6, then:

(a == 8) // evaluates to false, since a is not equal to 8


(a*b >= c) // evaluates to true, since (3*2 >= 6) is true
(b+4 > a*c) // evaluates to false, since (2+4 > 3*6) is false
((b=3) == a) // evaluates to true

int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3

5.5 Logical Operators ( !, &&, || )

Logical operators are used to determine the logic between variables or values. The return
value of a comparison is either true (1) or false (0). It is used together with relational operations.

Operator Name Description


Reverse the result, if the statement is true
! Logical NOT it will return false

Logical AND Returns true if all statements are true


&& Returns false if at least one of the
statement is false
Returns true if at least one statements is
|| Logical OR true
Returns false if all statements are false

The operator ! in C++ has only one operand, to its right, and inverts it, producing false if
its operand is true, and true if its operand is false. Basically, it returns the opposite Boolean
value of evaluating its operand.

Examples:

!(3 == 3) // evaluates to false because the expression at its


right(3 == 3) is true
!(8 <= 4) // evaluates to true because (8 <= 4) would be false
!true // evaluates to false
!false // evaluates to true

The logical operators && and || are used when evaluating two expressions to obtain a
single relational result. The operator && corresponds to the Boolean logical operation AND,
which yields true if both its operands are true, and false otherwise. The following panel shows
the result of operator && evaluating the expression a&&b:

35
Operators

&& OPERATOR (and)


A b a && b
True true true
True false false
False true false
False false false

The operator || corresponds to the Boolean logical operation OR, which yields true if either
of its operands is true, thus being false only when both operands are false. Here are the
possible results of a||b:

|| OPERATOR (or)
A b a || b
True true true
True false true
False true true
False false false

Examples:

((5 == 5) && (3 > 6)) // evaluates to false ( true && false )

((5 == 5) || (3 > 6)) // evaluates to true ( true || false )

5.6 Operators Precedence

If there are multiple operators in a single expression, from the left to right the operators
with higher precedence is evaluated first.

Example
:
X = 12 – 5 * 2 ; // Answer: 2

5 * 2 will be evaluated first since the multiplication operator ( * ) is of higher precedence


than the subtraction operator ( - ).

If you wish to evaluate 12 – 5 first, then we must enclosed them with parentheses.

X = (12 – 5) * 2 ; // Answer: 14

Note : When an expression has two operators with the same precedence /
level, grouping determines which one is evaluated first: either left-to-right or right-to-left.

Enclosing all sub-statements in parentheses (even those unnecessary because of their


precedence) improves code readability.

36
Operators

C++ Operators Precedence Table (taken from cplusplus.com)

From greatest to smallest priority, C++ operators are evaluated in the following order:

Level Precedence group Operator Description Grouping


Left-to-
1 Scope :: scope qualifier
right
++ -- postfix increment / decrement
() functional forms Left-to-
2 Postfix (unary)
[] subscript right
. -> member access
++ -- prefix increment / decrement
~ ! bitwise NOT / logical NOT
+ - unary prefix
Right-to-
3 Prefix (unary) & * reference / dereference
left
new delete allocation / deallocation
sizeof parameter pack
(type) C-style type-casting
Left-to-
4 Pointer-to-member .* ->* access pointer
right
Left-to-
5 Arithmetic: scaling * / % multiply, divide, modulo
right
Left-to-
6 Arithmetic: addition + - addition, subtraction
right
Left-to-
7 Bitwise shift << >> shift left, shift right
right
Left-to-
8 Relational < > <= >= comparison operators
right
Left-to-
9 Equality == != equality / inequality
right
Left-to-
10 And & bitwise AND
right
Left-to-
11 Exclusive or ^ bitwise XOR
right
Left-to-
12 Inclusive or | bitwise OR
right
Left-to-
13 Conjunction && logical AND
right
Left-to-
14 Disjunction || logical OR
right
= *= /= %= += -
= assignment / compound
Assignment-level >>= <<= &= ^= assignment Right-to-
15
expressions |= left
?: conditional operator
Left-to-
16 Sequencing , comma separator
right

37
Operators

Activities:

Evaluate the following expressions:

1. a = 6;
b = 10;
c = ++a * b--;

what are the values of a, b, and c? a =_______ b=________ c=_________

2. ! ( 5 * (10 / 2 ) >= 17 – 9 / 3 ) True or False

3. x = 3;
y = 7;
z = 8;
z += (x*y); x = ________ y = _______ z= _______

4. pupcet = 80;
hsAve = 78;
public = true;

(pupcet > 75 && hsAve > 80) || public True or False

5. 100 % 32 * 5 + 4 = _______

Write an expression using the appropriate operators for the following:

6. Convert the value in CENTIMETER to Inches.

________________________________________________

7. Get the AMOUNT to pay after deducting 20% to PRICE

________________________________________________

8. Ask whether STATUS is ‘M’ or ‘S’ and WORK is true.

________________________________________________

9. Get 35% of POPULATION.

_________________________________________________

10. Ask whether BRAND is “UNIQLO” and PRICE is less than 1000.

___________________________________________________

38
Operators

Online References

https://www.w3schools.com/cpp/cpp_operators.asp

https://www.tutorialspoint.com/cplusplus/cpp_operators.htm

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

39
Comments

UNIT 6: COMMENTS

Introduction

Comments are added to the program for the sake of the programmer. Comments are
ignored by the compiler. We add comments to tell who wrote the program, when was it written
or when last updated and to describe the function of the program. These comments help
anyone reading the source code. All programming languages allow for some form of comments.

Comments can occupy a single line or multiple lines. For each type, there are different
special characters to use to begin and end your comment line.

A program may or may not include comments but it always advisable to use them as a
form of documentation.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Write single and multiple lines comment.


2. Determine when and how to use single and multi lines comment in a program
3. Format comments so they will be easier to read.

Course Materials

6.1 Types of C++ Comments

Comments can be used to explain C++ code, and to make it more readable. It can also be
used to prevent execution of certain lines of code when testing alternative code. Comments can
be singled-lined or multi-lined.

Single-line comments start with two forward slashes (//). Any text between // and the
end of the line is ignored by the compiler (will not be executed). A line can only occupy
comments only or can be added after the statement/code.

Examples:

// Programmer: Juan dela Cruz

//Date last Updated: June 14, 202

40
Comments

// This program is used to compute the take-home pay of an employee

fg = (q1 + q2 + q3 + q4) / 4; //compute final grade

Multi-line comments start with /* and ends with */. Any text between /* and */ will be
ignored by the compiler.

Examples:

/* This program will compute the weekly salary of ABC Inc. employees. This program
should be run every Friday 6pm. Number of hours worked and hourly rate of the
employees are read from an input file. */

/ * Programmer: Juan dela Cruz


Date last Updated: June 14, 202
This program is used to compute the take-home pay of an employee. */

6.2 Using Comments When Debugging Your Program

When you are debugging your program or you want to try other codes but do not want to
erase the existing code, all you need to do is to make those codes as comments. In that way,
they will be ignored by the compiler. If the new code works, then you can permanently delete
the old codes.

Example

/* totalGrade = q1 +q2 +q3 + q4 ;


finalGrade = totalGrade / 4 ;
*/

finalGrade = (q1 +q2 +q3 + q4) / 4 ;

or

// totalGrade = q1 +q2 +q3 + q4 ;


// finalGrade = totalGrade / 4 ;

finalGrade = (q1 +q2 +q3 + q4) / 4 ;

41
Comments

Activities:

Change the format of the following comments to make them easier to read.

int number; // input count ______________________________


char c; // single character buffer ______________________________
char buffer[99]; // the input line ______________________________

/* *********************** __________________________
Program Name: Salary.cpp ______________________________
Programmer : Mr. XY Zhi ______________________________
Company: ABC Inc. ______________________________
************************* */

// ask user to input price ________________________________


cout << “Input Price: “; ________________________________
cin >> price; ________________________________
// ask user to input discount rate: ________________________________
cout << “Discount %: “; ________________________________
cin >> “discRate; ________________________________
//compute discount ________________________________
Discount = price * (disRate/100); ________________________________
________________________________
________________________________

Online References

https://www.programiz.com/cpp-programming/comments

https://www.geeksforgeeks.org/comments-in-c-c/

https://www.learncpp.com/cpp-tutorial/comments/

42
cout <<

UNIT 7: OUTPUT STATEMENT

Introduction

All computer programs created involve displaying something on your screen or monitor.
It can be the result of a computation, a prompt asking the user to enter something from the
keyboard or it can be a reminder or an instruction that the user must follow while using the
program.

When displaying something on your screen, make sure that it is readable, meaning there
are ample spacing between words and between lines. The instructions and prompt must be
clear and concise. Use words that are familiar to the user of your program.

Learning Objectives

After successful completion of this lesson, you should be able to:

a. Use cout in your program to display a message, an output or a prompt.


b. Differentiate the use of endl and \n.
c. Use other escape sequences together with cout

Course Materials:

7.1 cout statement

The cout command in C++ is use to display the output to a standard output device like
your monitor or screen. It is defined in the <iostream> header file. So, if you do not include
the lines: #include <iostream> and using namespace std; at the beginning of your
program, errors will appear when you compile your program and your program will not run.

The “c” in cout refers to “character” and “out” means “output”. The cout object is used
along with the insertion operator (<<) in order to display a stream of characters.

The general syntax is:

cout << varName;

or

cout << “some string”;

43
cout <<

The extraction operator (<<) can be used more than once with a combination of
variables, strings and manipulators (like endl or \n).

cout << “some string “ << varName << endl;

Note: After cout there should be an insertion operator (<<) and at the end of your statement
there must be a semicolon (;). You can put a space before and after the << to make your
statement more readable. Spaces between double quotation marks (“ “) are counted and
displayed. Press < (less than symbols) twice to make << (no space in between).

If you typed 10 spaces in between the words you want to display then you can see 10
spaces in your screen. The compiler will not truncate the excess spaces.

cout “Hello World!”;

will display:

Hello World!

Example 1

In this example, we will display a message on the first available line on your screen. The
message must be inside a double quotation mark (“ “).

#include <iostream>
using namespace std;
int main ()
{
cout << "Hello BSIT Batch 2020";
return 0;
}

The output of the program:

44
cout <<

Example 2

In this example, we will display the value of a variable. A variable can hold a numeric
value, a character or a string.

#include <iostream>
using namespace std;
int main ()
{
int year = 2020;
cout << year;
return 0;
}

Note: It is not a good programming habit to just display a value without describing
what it is to the user.

So instead of just using

cout << year;

you can write,

cout << “Current Year: “ << year;

To make your output more readable, insert at least one space before displaying the
value of your variable.

If you write: cout << “Current Year: “ << year;

The output will be: Current Year: 2020

If you write: cout << “Current Year:“ << year;

The output will be: Current Year:2020

45
cout <<

Example 3

In this example we combine a string and a variable in one cout statement.

#include <iostream>
using namespace std;
int main ()
{
int year = 2020;
cout << "Hello BSIT Batch " << year;
return 0;
}

Example 4

In this example we will use cout to display result of a direct computation.

#include <iostream>
using namespace std;
int main ()
{
int currentYear = 2020;
int birthYear = 1989;

cout << "Age: " << currentYear - birthYear;

return 0;
}

46
cout <<

7.2 Using endl and \n together with cout

Both endl and \n serve the same purpose in C++ – they insert a new line before they
display the next item or message. But an

endl must appear together with << and is outside the “ “ while \n must be inside
the “ “.

Example:

cout << “Hello” << endl << “World!”;

and

cout << ”Hello\nWorld!”

will produce the same output

Hello
World!

if you want to put a blank space in between lines your statement must be like this

cout << “Hello” << endl << endl <<“World!”;

or

47
cout <<

cout << ”Hello\n\nWorld!”

Hello

World!

Using endl and \n is like pressing the Enter key on your keyboard. To have multiple
blank lines in between your output you have to write down more than one endl or \n in your
cout statement Let’s say you want three blank lines between Hello World!, your cout <<
would be like this:

cout << “Hello” << endl << endl << endl << endl <<“World!”;

or

cout << ”Hello\n\n\n\nWorld!

Hello

World!

Note: How many endl or \n will you type if your want multiple blank lines between?
Answer: desired number of blank lines +1

7.3 Escape Sequences

The following escape sequences can be used along with the cout command

\' single quote


\" double quote
\? question mark
\\ backslash
\a audible bell

48
cout <<

\b backspace
\f form feed - new page
\n line feed - new line
\r carriage return
\t horizontal tab
\v vertical tab

Example 5

This program will show the effect of some of the above escapes sequences.

#include <iostream>
using namespace std;

int main ()
{
cout << "With endl--" << endl;
cout << "BSIT Batch 2020" << endl;

cout << endl << "With \\n" << endl;


cout << "BSIT Batch 2020 \n";

cout << endl << "With \\t" << endl;


cout << "BSIT \t Batch \t 2020" << endl;

cout << endl << "With \\b" << endl;


cout << "BSIT\bBatch\b2020" << endl;
cout << "BSIT \bBatch \b2020" << endl;
cout << "BSIT\b Batch\b 2020" << endl;

cout << endl << "With \\ \" " << endl;


cout << "\"BSIT Batch 2020\"" << endl;

cout << endl << "With \\' " << endl;


cout << "\'BSIT Batch 2020\' " << endl;

cout << endl << "With \\" << endl;


cout << "BSIT\\ Batch\\ 2020" << endl;

cout << endl << "With bell \\ a" << endl;


cout << "BSIT\a Batch\a 2020\a" << endl;

return 0;
}

49
cout <<

Activities

1. Edit the program in Example 3, the program should display 5 blank lines before
Batch 2020.

Hello BSIT

Batch 2020

2. Write a program that will display your first name, middle name and last name in
separate lines with blank space in between. Use only one cout statement.

Example output:

Roi Eldrick

De Jesus

Villanueva

50
cout <<

3. Write a program that declares the following integer values:

Infected = 25432
Recovered = 4235
Died = 1453

Then display the number of active cases.

Example screen output:

Corona Virus Report:

Infected = 25423
Recovered =4235
Died = 1453

Active Cases = ?

Online References

https://www.geeksforgeeks.org/escape-sequences-c/

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

https://www.programiz.com/cpp-programming/library-function/iostream/cout

51
cin>>

UNIT 8: INPUT STATEMENTS

Introduction

Data that we process are normally not part of our codes. Data for processing oftentimes
are inputted by the user or read from a file. We need to determine the types of data that will be
read or entered in order to make proper variable name declaration and initialization.

When asking user to input data, write a short prompt that will describe the data that
needs to be inputted. Without proper prompt, user may input the wrong type of data. Example:
with this prompt - Enter Section ( 1 – 5): the user will know that only numbers 1 to 5 are allowed.
But even with this prompt, user may sometimes accidentally press the wrong key on the
keyboard, so, it is a MUST to validate all the data that will be entered. Remember, GIGO!

Learning Objectives

After successful completion of this lesson, you should be able to:

4. Use the keyboard t0 Input data.


5. Write proper input prompts.
6. Determine when to use cin >> and getline() function.

Course Materials:

8.1 cin statement

The usual input device in a computer is the keyboard. C++ cin statement is the
instance of the class istream and is used to read input from the standard input device which is
usually a keyboard. Again, you cannot use cin statement without #include<iostream> at
the start of your program.

The extraction operator (>>) is used together with the object cin for reading inputs. The
extraction operator extracts the data from the object cin which is entered using the keyboard.

>> are two greater than symbols with no space in between.

Before we can ask the user to input a data, you need to declare a variable that will store
the data. Make sure to use the right data type. For example, your data will be a whole number
then you must use int instead of double. int uses only four bytes of your memory while double
occupies eight bytes.

52
cin>>

Example 1

The program declares and initializes 3 int variables: curYear is given a value of 2020,
birthYear and age are both 0 since their values are not known during the creation of the
program. The value that will be entered by the user will be stored in birthYear and the
result of the computation will be stored in variable age.

Before the command, cin >> birthYear; we display a prompt by issuing the
command cout << "Enter your birth year: "; the user will now know what data to
enter.

#include <iostream>

using namespace std;

int main()
{
int curYear =2020, birthYear =0, age = 0;

cout << "Enter your birth year: ";


cin >> birthYear;
age = curYear - birthYear;
cout << "\n\nYour age is: " << age;

return 0;
}

53
cin>>

Now, let us delete the line cout << "Enter your birth year: "; the program
will still run but the user will have no idea what to enter or press.

#include <iostream>

using namespace std;

int main()
{
int curYear =2020, birthYear =0, age = 0;

cin >> birthYear;


age = curYear - birthYear;
cout << "\n\nYour age is: " << age;

return 0;
}

When you run the program the initial screen will be like this:

There is only a blinking cursor on the first line, waiting for you to enter something. The
user unless he is the one who created the program will know what data to entered, if not, the will
be confused he might think there is something wrong with the program or will wait for something
to appear on the screen.

54
cin>>

If I press a letter, this will be the output.

Example 2

The program below will compute the salary of an employee based on the value of hours
worked and hourly rate entered. The value of tax rate is 20%. When you initialize a variable it
is not always zero or blank it can be another value, depending on the requirements of the
program.

You can also make taxRate as constant ( const float taxRate = 0.20;) Make
use of proper indentions and spacing to make your program more readable.

#include <iostream>
using namespace std;

int main()
{
// variable declaration and initialization
float taxRate = 0.20;
int hWork = 0;
float hRate = 0.0;
float gross = 0.0;
float tax = 0.0;
float salary = 0.0;

// data entry
cout << "Enter number of working hours: ";
cin >> hWork;
cout << "Enter hourly rate: ";

55
cin>>

cin >> hRate;

// computation
gross = hWork * hRate;
tax = gross * taxRate;
salary = gross - tax;

// display output
cout << "\n\nGross pay: " << gross;
cout << "\n Tax: " << tax;
cout << "\n Salary: " << salary;

return 0;
}

8.2 How to input string

String data type can be composed of more than one character. A character can be a
letter in lowercase (a-z) or uppercase (A-Z) , a digit (0 – 9), or a special character or symbol.
So, a string can be a combination of those characters. Aside from cin >> we can also use the
function getline(). Observe their difference when you run the program below.

Example 3

We use the program in Example 2 but added a string variable and another prompt and
cin statement. The program will run smoothly if the name you entered has no space in between
them.

56
cin>>

#include <iostream>
using namespace std;

int main()
{
// variable declaration and initialization
int hWork = 0;
float hRate = 0.0;
float gross = 0.0;
float tax = 0.0;
float taxRate = 0.20;
float salary =0.0;
string empName = "";

// data entry
cout << "Enter name of employee: ";
cin >> empName;
cout << "Enter number of working hours: ";
cin >> hWork;
cout << "Enter hourly rate: ";
cin >> hRate;

// computation
gross = hWork * hRate;
tax = gross * taxRate;
salary = gross - tax;

// display output
cout << "\n\n Employee: " << empName;
cout << "\nGross pay: " << gross;
cout << "\n Tax: " << tax;
cout << "\n Salary: " << salary;

return 0;
}

57
cin>>

Now, let us try inputting the whole name ex. Cardo Dalisay. This will be the outcome:

When you type Cardo Dalisay and then press the Enter key, the program will not ask
you anymore to enter the values for hours worked and hourly rate. Why? Using cin >> will only
read up to the first space it encounters. Thus, employee name is only Cardo, it ignores the
characters after the space (Dalisay). Those characters ignored are passed to the other variables
and since they are not numeric value they will consider them as zero.

Solution:

Instead of using cin>> empName; replace it with getline(cin, empName); the


function getline() will read up to last character before you press the Enter key. So we can
say that for string, cin>> looks for the space and getline() looks for the Enter key.

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

int main()
{
// variable declaration and initialization
int hWork = 0;
float hRate = 0.0;
float gross = 0.0;
float tax = 0.0;
float taxRate = 0.20;
float salary =0.0;
string empName = "";

// data entry
cout << "Enter name of employee: ";
getline(cin,empName);
cout << "Enter number of working hours: ";

58
cin>>

cin >> hWork;


cout << "Enter hourly rate: ";
cin >> hRate;

// computation
gross = hWork * hRate;
tax = gross * taxRate;
salary = gross - tax;

// display output
cout << "\n\n Employee: " << empName;
cout << "\nGross pay: " << gross;
cout << "\n Tax: " << tax;
cout << "\n Salary: " << salary;

return 0;
}

The syntax of getline() function is getline(cin, stringVariable); and at the


beginning of the program add #include <string> because the codes for getline() function is
in this header file.

Note: To be safe use getline() function when asking for data of type string and cin>> for
numbers char and other data types.

59
cin>>

Example 4

This program will ask the user to enter the name, section (char type), grades in first and
second grading, then compute and display the final grade of the student.

#include <iostream>
#include <string>
using namespace std;
int main()
{
// variable declaration and initialization
string studName = "";
char studSection = ' ';
float firstGrading = 0.0;
float secGrading = 0.0;
float finGrade = 0.0;

// data entry
cout << "Enter name of student: ";
getline(cin, studName);
cout << "Enter section (A-F): ";
cin >> studSection;
cout << "Enter grade during first grading: ";
cin >> firstGrading;
cout << "Enter grade during second grading: ";
cin >> secGrading;

// computation
finGrade = (firstGrading + secGrading)/2;

// display output
cout << "\n\n Student: " << studName;
cout << "\n Section: " << studSection;
cout << "\n\n Final Grade: " << finGrade;

return 0;
}

60
cin>>

Activities

Write program lines to display prompt and allow user to enter the data.

1. Number of students enrolled in first year.


2. Name of hospital
3. Percentage of population affected by covid-19
4. Delivery charge for item ordered online
5. Floor area of a house

Programming

1. Write a C++ program that asks the user to enter two numbers, obtains the two numbers
from the user, and prints the sum, product, difference and quotient of the two numbers.

2. Write a C++ program that asks the user to enter the number of miles driven and gallons
used for each full tank. The program should calculate and display the miles per gallon
obtained for each full tank.

3. Write a C++ program that will compute and display the take home pay of an employee.
You need to enter the name of the employee, the total number of hours worked, the
hourly rate and the tax rate.

4. A salesperson needs to compute the number of tiles a customer should buy. The
salesperson must know the length and width of the floor in meters and the size of the tile

61
cin>>

(length and width in centimeter) the customer chose to buy. Write a C++ program to
accomplish this task.

5. How much must a senior citizen pay for the medicines he/she bought if all requirements
are presented to the drugstore? The program must ask the user to enter the total cost of
medicines. Compute and display the discounts and the amount to be paid by the senior.
(Philippine setting – do some research  )

Online References

http://www.cplusplus.com/reference/iostream/cin/

https://www.w3schools.com/cpp/cpp_user_input.asp

https://www.learncpp.com/cpp-tutorial/introduction-to-iostream-cout-cin-and-endl/

62
If and switch

UNIT 9: CONDITIONAL STATEMENTS

Introduction

Programs are executed from top to bottom (linear sequence). But as our problem or
requirements become complex, our programs more often than not will have to make decisions
to skip some of its parts and jump to some part depending on the answer after evaluating the
conditional statement that we provide. This is the part where we can apply the relational and
logical operators we discussed in the previous lesson.

Decision making or selection structure requires a programmer to specify one or more


conditions to be evaluated along with the statement/s that will be executed if the condition is
true. Optionally, the programmer may also provide statement/s that will be executed if the
evaluation is false.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Apply the use of relational and logical operators in writing conditional statements.
2. Define the format of if, if...else, switch, nested if and nested
switch statement.
3. Determine what conditional statement to use to satisfy all the requirements of the
program.

Course Materials

C++ programming language provides following types of decision making statements:

1. if statement - consists of a boolean expression followed by one or more


statements.
2. If…else statement - is an ‘if’ statement followed by an optional ‘else’ statement,
which executes when the boolean expression is false.
3. switch statement - allows a variable to be tested for equality against a list of values.
4. nested if - one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).
5. nested switch statement - one ‘switch’ statement inside another ‘switch’ statement(s).

63
If and switch

9.1 if statement Use the if statement to specify a block of C++ code to be executed if a
condition is true.

condition

True

False
Conditional
codes

Syntax:

if (condition) {
// block of code to be executed if the condition is true
}

Examples:

Determine if a person is a Senior Citizen based on age.

int age =0 ;
:
cin >> age;
if (age >= 60){
cout << “SENIOR CITIZEN”;
}

64
If and switch

Give 20% discount if customer is a senior citizen

int age =0 ;
float price = 0.0;

cin >> age;


:
cin >> price;
if (age >= 60){
cout << “price discounted! “;
price = price – (price * 0.20);
}
cout << “\nPlease pay: “ << price;

9.2 if … else statement Use the else statement to specify a block of code to be executed if
the condition is false.

False
Conditional
condition codes

True

Conditional
codes

Syntax:

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

65
If and switch

Examples:

Determine if a person is a MINOR or an ADULT based on age

int age =0 ;
:
cin >> age;
if (age < 18){
cout << “MINOR”;
} else {
cout << “ADULT”;
}

Note: if there is only ONE statement for true or for false it is ok not to include the braces. Use
indentions to make your program easier to read and debug. Usual error – ‘else without if’

if (age < 18)


cout << “MINOR”;
else
cout << “ADULT”;

if (age < 18)


cout << “MINOR”; PLEASE TYPE YOUR PROGRAM LIKE
else THIS!!!!
cout << “ADULT”;

Also note that conditions are written inside the parentheses () and there is no semicolon
after the close parenthesis.

float moSalary =0.0;


int yearService = 0;
float loan =0.0;
:
cin >> moSalary;
:
cin>> yearService;
:
if (moSalary > 20000 && yearService >=3)
loan = moSalary * 0.50;
else
loan = moSalary * 0.15;

cout<< “\nApproved Loan: “ << loan;

66
If and switch

9.3 if else if ladder Several if + else structures can be concatenated with the intention of
checking a range of values.

True
Conditional
condition codes

False

True
Conditional
condition codes

False

Conditional
codes

Syntax:

if (condition) {
// block of code to be executed if the condition is true
} else if (condition){
// block of code to be executed if the condition is false
} else
// block of code to be executed if the condition is false
}

Note: This is NOT limited to two if (condition)

67
If and switch

Examples:

Determine if a number is positive, negative or zero.

cin >>x;
if (x >0)
cout << “x is positive”;
else if (x < 0)
cout << “x is negative”;
else
cout << “x is zero”;

Determine the equivalent grade in SIS

cin>> grade;

if (grade >= 97)


sis = 1.0;
else if (grade >= 94)
sis = 1.25;
else if (grade >= 91)
sis = 1.50;
else if (grade > = 88)
sis = 1.75;
else if (grade >= 85)
sis = 2.0;
else if (grade >= 82)
sis = 2.25;
else if (grade >= 79)
sis = 2.50;
else if (grade >=76)
sis = 2.75;
else if (grade >=75)
sis = 3.00;
else sis = 5.00;

68
If and switch

9.4 Nested if Nested if statements mean an if statement inside another if statement.

Syntax:

if (condition1) {
// block of code to be executed if the condition is true
if (condition2){
// block of code to be executed if the condition is false
} else
// block of code to be executed if the condition is false
}

Examples

float moSalary =0.0;


int yearService = 0;
float loan =0.0;
:
cin >> moSalary;
:
cin>> yearService;
:

if (moSalary > 20000)


if (yearService >=3)
loan = moSalary * 0.50;
else
loan = moSalary * 0.30;
else
loan = moSalary * 0.15;

cout<< “\nApproved Loan: “ << loan;

float pupcet =0.0;


float seniorGrade =0.0;
:
cin >> pupcet;
:
cin>> seniorGrade;
:
if (pupcet > 75)
if (seniorGrade > 85)
cout << “Admitted”;
else
cout << “Denied Admission”;

69
If and switch

For pupcet = 90 and seniorGrade = 90 --- Admitted

For pupcet = 90 and seniorGrade = 80 ---- Denied Admission

For pupcet = 70 and seniorGrade = 90 ----- NO OUTPUT!

70
If and switch

Why?

if (pupcet > 75)


if (seniorGrade > 85)
cout << “Admitted”;
else
cout << “Denied Admission”;
// no corresponding else

Remedy

if (pupcet > 75.0)


if (seniorGrade > 85.0)
cout << "\n\nAdmitted";
else
cout << "\n\nDenied Admission";
else
cout << "\n\nDenied Admission";

9.5 switch statement - A switch statement allows an expression to be tested for equality
against a list of values. Each value is called a case, and the expression being switched
on is checked for each case.

Syntax:

switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional

71
If and switch

// you can have any number of case statements.


default : //Optional
statement(s);
}

The following rules apply to a switch statement −https://www.tutorialspoint.com/


 The expression used in a switch statement must have an integral or enumerated type,
or be of a class type in which the class has a single conversion function to an integral or
enumerated type.
 You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
 The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.

Examples:

Determines if a number is EVEN or ODD.

int number=0;

cout <<"\nEnter a whole number: ";


cin >> number;

switch (number % 2) {
case 0: cout << "\n EVEN number";
break;
case 1: cout << "\n ODD number";
}

72
If and switch

Determine monthly subscription fee based on plan ( A- C)

char plan = '';


int freecallSameNet = 0;
float callRate = 0.0;

cout <<"\nEnter a plan [ A- C ]: ";


cin >> plan;

switch (plan)
{
case 'a':
case 'A': mfee = 700.00;
freecallSameNet = 20;
callRate = 7.00;
break;
case 'b':
case 'B': mfee = 900.00;
freecallSameNet = 40;
callRate = 6.50;
break;
case 'c':
case 'C': mfee = 1200.00;
freecallSameNet = 60;
callRate = 6.00;
break;

default: cout << "Wrong plan entered. Try again!";


}

Equivalent with an if statement

if (plan =='a' || plan == 'A') {


mfee = 700.00;
freecallSameNet = 20;
callRate = 7.00;
} else if (plan =='b' || plan == 'B') {
mfee = 900.00;
freecallSameNet = 40;
callRate = 6.50;
}else if (plan =='c' || plan == 'C') {
mfee = 1200.00;
freecallSameNet = 60;
callRate = 6.00;
}else
cout << "Wrong plan entered. Try again!";

73
If and switch

9.6 Nested switch is/are switch statement within a switch statement.

Consider the table below:

Course # and Year Tuition Fee per Miscellaneous


Description Level Unit Fee

1 - BSA 1 324.65 4545.77


2 456.32 5664.65
3 432.76 3565.78
4 345.76 5645.76
2 - BSIT 1 546.76 3453.67
2 657.89 5656.78
3 767.90 6577.78
4 665.87 4564.78
0 - Other All 565.78 7656.78
Courses level

Input course #, year level, number of units enrolled, then compute and display the amount
to pay.

# include<iostream>
using namespace std;

int main()
{
int cNo = 0, Ylevel = 0, units =0;
float tuitionfee = 0.0, miscFee= 0.0, amt2Pay=0.0, error=0;

cout <<"\nCourse No. Description ";


cout <<"\n\n 1 BSA ";
cout <<"\n 2 BSIT";
cout <<"\n 0 Other courses";
cout <<"\n\n Enter course number: ";
cin >> cNo;
cout <<"\nEnter year level: [ 1 - 4 ]: ";
cin >> Ylevel;
cout << "\nNumber of units enrolled: ";
cin >> units;

switch (cNo)
{
case 1: switch(Ylevel)
{
case 1: tuitionfee = units* 324.65;
miscFee = 4545.77;
break;
case 2: tuitionfee = units* 456.32;
miscFee = 5664.65;
break;

74
If and switch

case 3: tuitionfee = units* 432.76;


miscFee = 3565.78;
break;
case 4: tuitionfee = units* 345.76;
miscFee = 5645.76;
break;
default: cout << "\n\nWrong year level for BSA";
error = 1;
} break;

case 2: switch(Ylevel)
{
case 1: tuitionfee = units* 546.76;
miscFee = 3453.67;
break;
case 2: tuitionfee = units* 657.89;
miscFee = 5656.78;
break;
case 3: tuitionfee = units* 767.90;
miscFee = 6577.78;
break;
case 4: tuitionfee = units* 665.87;
miscFee = 4564.78;
break;
default: cout << "\n\nWrong year level for BSIT";
error =1;
} break;

case 0: if (Ylevel > 0 && Ylevel <5)


{
tuitionfee = 565.78;
miscFee = 7656.78;
} else {
cout << "\n\nWrong year level for Other Courses.";
error =1;
}
break;

default: cout << "\n\nWrong course number.";


error = 1;
}
if (!error) {
cout << "\n\n\n Please pay:";
cout << "\n\n Tuition Fee: " << tuitionfee;
cout << "\n\n Miscellaneous Fee: " << miscFee;
cout << "\n\n TOTAL: " << tuitionfee + miscFee;
}
return 0;
}
Note: error variable added as flag to catch if there was an error in the data entry. If wrong
data were entered no amount should be displayed.

75
If and switch

Activities

Write C++ statements for the following conditions: (declare and initialize variables that you
will be using before writing the if statement)

1. Write an if statement that displays the string “Firetree” if the user enter the letter F (in any
case).
2. Write an if statement that displays the string “Entry error” if the user enters a number that is
less than 0; otherwise, display the string “Valid number”
3. Write an if statement that displays the string “Reorder” if the user a number less than 10;
otherwise display the string “OK”
4. Write an if statement that assigns the number 10 to the bonus variable if the user enters a
sales amount that is less than or equal to $250. If the user enters a sales amount that is
greater than $250, prompt the user to enter the bonus rate, and then multiply the user’s
response by the sales amount and assign the result to the bonus variable.
5. Write an if statement that displays the string “Valid entry” when the user enters either the
integer 1, the integer 2, or the integer 3; otherwise, display the string “Error entry”
6. Write an if statement to test if the input data (two meter readings) is valid. To be valid, both
meter readings must be greater than zero, and the current meter reading must be greater
that the previous reading. If the data is not valid, display an appropriate error message.
7. Write an if statement to test if the number of registrants is greater than zero but less than 50.
Display an appropriate error message if the number of registrants is invalid.
8. Write an if statement that will display the shipping charge based on the province entered by
the user. If the user enters any other state, the result should be an “Incorrect state” message.

Province Shipping Charge (Php)

Laguna 130

Cavite 130

9. 9. Write an if statement that will display the shipping charge based on the province entered
by the user. If the user enters any other state, the shipping charge should be 0..

Province Shipping Charge (Php)

Batangas 250

Quezon 300

76
If and switch

Programming Exercises

1. Write a C program the will determine the total amount the company owed using an if.
The seminar fee per person is based on the number of people the company registers, as
showed in the table below. (For example, if the company registers seven people, then
the total amount owed by the company is Php 12600.00

Number of Registrants Fee Per Person

1–4 Php 2000.00

5 – 10 Php 1800.00

11 or more Php 1500.00

2. Write a C program that will ask the user to input the following: total monthly income,
total monthly expenses, preferred model house (A,B or C) and mode of payment (C –
cash or I – installment). Please refer to the table below to see if loan will be granted or
not and how much will a customer pay if cash payment was chosen.

House Model Total Contract Price Down Payment Monthly Amortization

A 3,563,890.00 30% of TCP 25,789.00

B 2,678,400.00 20% of TCP 20,675.00

C 1,980,700.00 15% of TCP 18,763.00

For a loan to be granted monthly amortization must be less than (total monthly income
less total monthly expenses). A 5% discount from the TCP price is given if mode is cash
basis.

Examples:

Total Monthly Income: 156,900.00

Total Monthly Expenses: 113,560.00

House Model (A, B or C): A

Mode of Payment (C or I): C

77
If and switch

Total Contract Price: 3,563,890.00

Discount: 178,194.50

Balance: 3,385,695.50

--------------------------------------------

Total Monthly Income: 156,900.00

Total Monthly Expenses: 113,560.00

House Model (A, B or C): A

Mode of Payment (C or I): I

Total Contract Price: 3,563,890.00

Down Payment: 1,069,167.00

Monthly Amortization: 25,789.00

LOAN APPROVED! Congratulation!

--------------------------------------------

Total Monthly Income: 156,900.00

Total Monthly Expenses: 136,450.00

House Model (A, B or C): A

Mode of Payment (C or I): I

Total Contract Price: 3,563,890.00

Down Payment: 1,069,167.00

Monthly Amortization : 25,789.00

Sorry LOAN DENIED!

78
If and switch

Online References

https://www.w3schools.com/cpp/cpp_conditions.asp/

https://ecomputernotes.com/cpp/control-structures/conditional-statements

https://www.programiz.com/cpp-programming/if-else

79
for loop

UNIT 10: LOOPING (for statement)

Introduction

Certain situations call for a block of codes or statements to be executed several times,
we refer to this as looping. All programming languages allow several options for you to do it. for,
while and do…while are available in C++, the concept on how to use them are all the same for
all computer languages, there is only a slight difference in their syntax or format. The loop stops
when a certain condition/s is satisfied.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Use for statement for repetitive task


2. Identify the limitations of for statement
3. Determine the applications where for statement are best suited

Course Materials

10.1 for statement allows you to execute a block of codes for a fix number of times. When
using this statement you must know in advance how many times to loop. Of course,
there is a way not to finish the loop (by using break statement) in case certain
situation/s requires them. Condition/s must be provided so the program knows when to
terminate the loop.

Block of
codes

True
?

False
80
for loop

Syntax:

for (statement 1; statement 2; statement 3) {


// code block to be executed
}

statement 1 – initializes the control variable (int or char type), executed only once
at the start of loop.

statement 2 – conditional statement, decides whether to continue the loop or not


executed after statement1 and after each statement 3. Here, you question
the value of the control variable.

statement 3 – executed after executing the block of codes. This should increment or
increment the value of the variable in statement 1.

Examples:

// prints the number 0 to 4 0


for ( i = 0; i < 5; i++) 1
2
cout << i << endl; 3
4

// prints the number 0 to 5 0


1
for ( i = 0; i <= 5; i++) 2
cout << i << endl; 3
4
5

// find the sum of the 1 to 5


total = 0; 1
2
for ( i = 1; i <= 5; i++){
3
cout << i << endl; 4
total = total + i; 5
} Sum: 15
cout << “Sum: “ << total;

// prints the letters of the English alphabet


for( i = ‘a’; i <= ‘z’; i++)
cout << i << “ “;

abcdefghIjklmnopqrstuvwxyz

81
for loop

// find the average grade in the class

int noStud = 0, total = 0;


float grade = 0.0, aveGrd = 0.0;
:
.
cout << “How many students in the class: “;
cin >> noStud;
for (int i = 1 ; i<= noStud; i++)
{
cout << “\nEnter grade of student #” << “ “;
cin >> grade;
total += grade;
}
aveGrd = total / noStud;
cout << “\n\nAverage grade in the class: “ << aveGrd;

How many students in the class: 5


Enter grade of student #1: 90.76
Enter grade of student #2: 86.52
Enter grade of student #3: 78.10
Enter grade of student #4: 82.45
Enter grade of student #5: 93.60

Average grade in the class: 86.286

10.2 Nested for loop – is a for loop statement within another for loop statement

Syntax:

for (statement 1; statement 2; statement 3) {

for (statement 1; statement 2; statement 3) {

// code block to be executed


}

// code block to be executed


}

Note: the variable that controls both loops must be different.

82
for loop

// prints the number 1 to 5 repeatedly according to its value

1
for ( i = 1; i <= 5; i++) Next
22
{
Next
for ( j = 1; j <= i j++) 333
{ Next
cout << i; 4444
Next
} 55555
cout << “\nNext\n”;
}

Enter how many students and number of examinations given to the students.
Compute average of students. Determine if the student PASSED or FAILED.

# include<iostream>
using namespace std;

int main()
{
int students = 0, exams = 0;
float total = 0.0, score= 0.0, average = 0.0;

cout << "\nHow many students in the class: ";


cin >> students;
cout <<"\nHow many examinations given: ";
cin >> exams;

for(int i =1; i <= students; i++)


{
total = 0.0;
cout << "\nEnter scores in Examination for student #" <<i
<<endl;
for (int j=1; j <= exams; j++)
{
cout << "\nExam #" << j << ":";
cin >> score;
total += score;
}
average = total/exams;
if (average >= 75)
cout << "\nPASSED\n";
else
cout << "\nFAILED\n";
}
return 0;
}

83
for loop

10.3 Infinite for loop – is a loop that has no end. The condition will never become false so
the statement inside the loop will just repeat until you press the CTRL + C keys in the
keyboard. You can use the for(;;) to signify an infinite loop.

Example:

for (; ;){
cout << “\nThis loop will run forever!”;
}

This loop will run forever!


This loop will run forever!
This loop will run forever! How to stop the loop
This loop will run forever! and continue with the
This loop will run forever!
This loop will run forever! rest of the program?
This loop will run forever!
This loop will run forever!
This loop will run forever!

break; Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.

for ( statement1; statement2; statement3 {


statement;
:
break;
statement;
:
}
statement;

84
for loop

Example:

Display a triangle made of asterisk. Input base of triangle (the number of asterisk
at bottom of the triangle). We use for (; ;) in validating our input, the program will break
or exit the loop if the inputted value is valid, otherwise it will continue to ask the user to
enter another value.

#include<iostream>
using namespace std;

int main()
{
int base, space, asterisk;

for (; ;)
{
cout << "Input base of triangle (3, 5, 7 or 9 only): ";
cin >> base;
if (base >=3 && base <= 9 && base % 2 ==1)
break;
}
cout << "\n\nTriangle with the base of "<< base << endl << endl;

space = base / 2;
asterisk =1;
for (int line = 1; line <= base/2+1; line++)
{
for( int s=1; s<=space; s++)
cout << " ";
for ( int a =1; a <= asterisk; a++)
cout << "*";
cout << endl;
space--;
asterisk+=2;
}

return 0;
}

85
for loop

continue; Causes the loop to skip the remainder of its body and immediately retest
its condition prior to reiterating.

In here, we reverse the condition in the if statement, if it is true then we continue or


ask for another value, otherwise we issue break. Without else break the loop will just
keep on repeating.

for (; ;){

cout << "Input base of triangle (3, 5, 7 or 9 only): ";


cin >> base;
if (base <3 || base > 9 || base % 2 !=1)
continue;
else
break;
}

Activities

Write a program segment using for loop

1. To display the first 10 integers that are divisible by 10.

2. To display all odd numbers in 0 to 100 backwards.

3. To get the age of 100 residents and count how many are senior citizens.

4. To get the sum of the number of gifts received in the song 12 Days of Christmas

5. To get the average score of 15 examinees.

86
for loop

Programming Exercises

1. Write a C program the will ask the user to enter an integer value between 5 and 10.
Then print the character ‘@’ in this order:

If the value inputted is 6, the output will be:

@@@@@@ @@@@@@

@@@@@ @@@@@

@@@@ @@@@

@@@ @@@

@@ @@

@ @

2. Ask the user to enter a name (one word only) and then print the name in the form of
letter ‘V’

Example:

Enter a name: Raizel

R R
a a
i i
z z
ee
l

3. Write a program that asks the user to type an integer N and then display the number of
prime numbers lesser or equal to N.

Enter a number: 35

1 2 3 5 7 11 13 17 23 29 31

87
for loop

4. Write a program that will ask the user to enter a short phrase or sentence (max 200
chars) and then count the number of words, vowels, consonants and space.

Enter a phrase or sentence: the quick brown fox jumps over the lazy dog
Words = 9
Vowels = 11
Consonants =24
Spaces = 8

5. Write a program that asks the user to type the value of N and computes N! .

The factorial of a non-negative


negative integer n, denoted by n!, is the product of all positive integers
gers less than or equal to n.

For example,

The value of 0! is 1, according to the convention for an empty product.

Online References

https://beginnersbook.com/2017/08/cpp
https://beginnersbook.com/2017/08/cpp-for-loop/

https://www.w3schools.com/cpp/cpp_for_loop.asp

https://www.programiz.com/cpp-programming/for
programming/for-loop

88
while and do…while loop

UNIT 11: LOOPING ( while and do…while statement)

Introduction

In general, statements are executed sequentially: The first statement in a function is


executed first, followed by the second, and so on. But more often than not your program will
have to choose a certain path and may have to repeat executing some of its statement until a
condition is satisfied. Programming languages provide various control structures that allow for
more complicated execution paths, like, for, while and do…while statement.
A loop statement allows us to execute a statement or group of statements multiple times.
If you do not know in advance how many times a block of codes will be executed then it is not
advisable to use a for loop. You can either use while or do while loop.

Learning Objectives:

After successful completion of this lesson, you should be able to:

1. Apply while and do… while for repeating codes.


2. Know when is the best time to use for, while and do…while statement.

Course Materials:

11.1 while loop - Repeats a statement or group of statements while a given condition is
true. It tests the condition before executing the loop body.

Syntax:

while (condition) {
// statements/codes to be executed
}

do …while loop - Like a ‘while’ statement, except that it tests the condition at the end
of the loop body.

Syntax:

do {
// statements/codes to be executed
}
while (condition);

89
while and do…while loop

Let us first convert our examples in the for loop lesson to while and do…while statement.

// prints the number 0 to 5

for ( i = 0; i <= 5; i++)


cout << i << endl;

//using while statement 0


i=-1; 1
2
while ( i < 5){ 3
i = i + 1; 4
5
cout << i << endl;
}

//using while statement


i=0;
while ( i <= 5){
cout << i << endl;
i = i + 1;
}

// find the sum of the 1 to 5


1
2
total = 0;
3
for ( i = 1; i <= 5; i++){ 4
cout << i << endl; 5
total = total + i; Sum: 15
}
cout << “Sum: “ << total;

int total =0;


int i = 0;
If int i = 1, how will
while( i < 5) { you construct your
i = i + 1; while loop?
cout << i << endl;
total = total + i;
}
cout << “Sum: “ << total;

90
while and do…while loop

int total =0;


int i = 0; If int i = 1, how will
you construct your
do { while loop?
i = i + 1;
cout << i << endl;
total = total + i;
} while ( i < 5);
cout << “Sum: “ << total;

// find the average grade of students in the class

How many students in the class: 5


Enter grade of student #1: 90.76
Enter grade of student #2: 86.52
Enter grade of student #3: 78.10
Enter grade of student #4: 82.45
Enter grade of student #5: 93.60

Average grade in the class: 86.286

// using while loop

int noStud = 0, total = 0, i= 0;


float grade = 0.0, aveGrd = 0.0;

cout << “How many students in the class: “;


cin >> noStud;
while (i< noStud) {
i=i +1;
cout << “\nEnter grade of student #” << i << “ “;
cin >> grade;
total += grade;
}
aveGrd = total / noStud;
cout << “\n\nAverage grade in the class: “ << aveGrd;

91
while and do…while loop

// using the do while loop

int noStud = 0, total = 0, i=0;


float grade = 0.0, aveGrd = 0.0;

cout << "How many students in the class: ";


cin >> noStud;
do {
i = i + 1;
cout << "\nEnter grade of student #" << i << " ";
cin >> grade;
total += grade;
} while (i< noStud);
aveGrd = total / noStud;
cout << "\n\nAverage grade in the class: " << aveGrd;

Note: the counter or variable i in the for loop needs to be incremented inside the while
and do while loop to reach the maximum needed value. You can use another variable name for
the counter. There is also NO semicolon at the end of the while loop but, there is one at the end
of do… while loop.

We can also use the while loop in validating our data entry. For example, the only valid
entries are the numbers 1 – 5. Instead of just issuing cin >> number; we can add while or
do…while loop so the program will keep on asking the user to enter another number if a
number outside 1 – 5 was entered.

Choice [1-5]: 9
Invalid Input. Try again!
Choice[1-5]: 7
Invalid Input. Try again!
Choice[1-5]: 3
OK

int choice=0;

cout << "Choice [1-5]: ";


cin >> choice;

//test if choice is valid


while (choice < 1 || choice > 5) {
cout << "Invalid input. Try again. \n\n";
cout << "Choice [1-5]: ";
cin >> choice;
}
cout << "OK";

92
while and do…while loop

// if choices are letters from A to E. Small letters a to e are considered invalid in the code
below:

char choice=' ';

cout << "Choice [A-E]: ";


cin >> choice;
//test if choice is valid
while (choice < 'A' || choice > 'E') {
cout << "Invalid input. Try again. \n\n";
cout << "Choice [A=E]: ";
cin >> choice;
}
cout << "OK";

// to include small letters ( a to e ) as valid entries add the function toupper()in your
condition. This will convert temporarily the entry to capital letter.

while (toupper(choice) < 'A' || toupper(choice ) > 'E')

// If the choice or values to be entered are not in sequence. Example, gender ‘M’ for
male and ‘F’ for female

char gender=' ';


cout << "Gender [M or F]: ";
cin >> gender;
//test if choice is valie
while (toupper(gender) != 'M' && toupper(gender) != 'F') {
cout << "Invalid input. Try again. \n\n";
cout << "Gender [M or F]: ";
cin >> gender;
}
cout << "OK";

93
while and do…while loop

11.2 Nested while loop

while (condition) {
while (condition) {
// statement(s) of inside loop
}
// statement of outer loop
}

Nested do…while loop

do {
do {
// statement of inside loop
}while(condition);
// statement of outer loop
} while(condition);

Note: there can be any type of loop nested inside any type and to any level

do{
while(condition) {
for (statement1; statement2; statement3) {
//statement inside for loop
}
// statement of inside while loop
}
// statement of outer do…while loop
}

Example: Assuming you don’t know how many students to process. Enter their grades for each
quarter compute and display their average and then count and display how many students
passed and failed in the class.

# include<iostream>
using namespace std;

int main(){

int i=0, j=0;


int pass=0, fail=0;
char more = ' ';
float total = 0.0, grade= 0.0, average = 0.0;

94
while and do…while loop

do {

i++;
total = 0.0;
cout << "\n Enter quarterly grades of student #" <<i <<endl;

for (j=1; j <= 4; j++){


cout << "\n Quarter #" << j << ":";
cin >> grade;
total += grade;
}

average = total/4;
cout << "\n\n Average grade: " << average;
if (average >= 75) {
pass++;
cout << "\n PASSED\n";
}
else {
fail++;
cout << "\n FAILED\n";
}

cout << "\n\n More students to process ? [Y/N]: ";


cin >> more;
while (toupper(more)!='Y' && toupper(more)!='N'){
cout << " Invalid entry!";
cout << "\n\n More students to process ? [Y/N]: ";
cin >> more;
}
} while (toupper(more) == 'Y');

cout << "\n\n No. of students who passed: " << pass;
cout << "\n No. of students who failed: " << fail;

return 0;
}

95
while and do…while loop

Activities

Examine the following code. What will the code display in the monitor?

1. int count = 0;
while ( count <= 6 )
{
cout << count;
count += 2;
}

2. int count = 7;
while ( count >= 4 )
{
cout << count;
count -= 2;
}

3. int count = 1;
while ( count < 5 )
{
cout << count;
}

4. Convert the following statements using while and do while.

sum = 0;

for (I = 0 ; I <= 100; I+=2) {

sum = sum + I;

cout << I << endl;

cout << endl << sum;

5. Using while statement ask the user to input a character, accept only characters ‘Y’ or ‘N’,
if other characters were inputted ask the user to enter another character again. Sample
Screen below:

Do you want t try again [Y or N ] ? M

Invalid entry! Only characters Y or N are accepted.

96
while and do…while loop

Do you want t try again [Y or N ] ? Y

Thank you. You may now proceed.

Programming Exercises

Write a program that will incorporate while or do…while statements to do the following:

- Enter total monthly income of families in a barangay


- Ask if there is a PWD or a Senior Citizen in a family
- Ask how many members for each family.
- Determine if a family can avail of the SAP worth Php 8000.00
o Conditions - there is a PWD or senior citizen or
Monthly income less than 10,000 and family members > 4

Family Monthly Income: __35000_____________

How many members of the family? ___5____

Is there a PWD or senior citizen in the family ( Y / N )? __Y___

SAP Php 8,000.00: Approved

More Entry [Y/N] ? __Y_

Family Monthly Income: __15000_____________

How many members of the family? ___2____

Is there a PWD or senior citizen in the family ( Y / N )? __N___

SAP Php 8,000.00: Disapproved

More Entry [Y/N] ? __Y_

97
while and do…while loop

Online References

https://www.tutorialspoint.com/cplusplus/cpp_while_loop.htm/

https://www.cprogramming.com/tutorial/lesson3.html

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

98
Array

UNIT 12 : Array

An array is a group or collection data of same data types. For example an int array
holds the elements of int types while a double array holds the elements of double types.

C Array – Memory representation

One-Dimensional Array is represented by a row with several columns.

https://beginnersbook.com/2014/01/c
https://beginnersbook.com/2014/01/c-arrays-example/

Two-Dimensional Array

https://www.geeksforgeeks.org/multidimensional
https://www.geeksforgeeks.org/multidimensional-arrays-c-cpp/

An array of arrays is known as 2D array. The two dimensional (2D) array in C.


Programming is also known as matrix. A matrix can be represented as a table of rows and
columns.

99
Array

Three-Dimensional Array

https://www.geeksforgeeks.org/multidimensional-arrays-c-cpp/

Three-Dimensional array is same as that of Two-dimensional arrays. The difference is


as the number of dimension increases so the number of nested braces will also increase.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Declare and initialize an array.


2. Put values in the array.
3. Manipulate the contents of an array

Course Materials

12.1 An array is a collection of data of the same type stored at contiguous memory location.
Each data can be accessed individually by using an index. The size of the array is declared at
the beginning of the program and cannot be change during the program execution. Array must
accommodate all data to be processed, so, it is better to declare an array of bigger size if you
do not know exactly the number of data items to process.

98 78 83 88 79 93 89
0 1 2 3 4 5 6

Array indices

100
Array

An array index always starts with 0. So, if the size of the array is 7 the last index is 6 or if
size is 100 then last index is 99.

Why do we need an array?

More often than not program process the same type of data repeatedly. Let’s say, there
are 50 students in the class and you need to compute their final grade and then later on you
want to list their names with their grades alphabetically or in descending (highest to lowest)
order based on the grade. Before, we only use one variable for the name and one variable for
the grade that can only hold one value at time and then we use looping so we could enter
another set of name and grade, but when another value was entered the previous value are
erased in the memory and will be replaced by the new value entered. We can declare 50
variables for the name, 50 for the grade, but, that will be tedious. The solution for this kind of
process is to use an array. We use the same name of variable for all students, just imagine that
it will be divided into how many times you want it to be.

For now, let us concentrate on one-dimensional array.

12.2 Array Declaration and Initialization

Syntax:

data_type arrayName[size];

OR data_type arrayName[] = {list of elements};

OR data_type arrayName[size] = {list of elements};

Examples:

int age[10];

0 1 2 3 4 5 6 7 8 9

int age[] = {6,72,47,13,23};

6 72 47 13 23
0 1 2 3 4

//size depends on the number of items listed during declaration

101
Array

int age [10] = {0};

0 0 0 0 0 0 0 0 0 0

0 1 2 3 4 5 6 7 8 9

int age[10] = {6,72,47,13,23};

6 72 47 13 23 0 0 0 0 0

0 1 2 3 4 5 6 7 8 9

char initial[3] = {‘‘};

0 1 2

float price[5] = {0.0};

0.0 0.0 0.0 0.0 0.0

0 1 2 3 4

string studName[50] = {“ “};

0 1 2 3 4 5 6 … 48 49

12.3 Assigning Value to an array

Direct:

studName[3] = “Beniah”;

Allowing user to enter values for the array:

int i, size =5;


string stud_name[5] = {" "};
int age[5] = {0};
float grade[5] = {0.0};

102
Array

for(i=0; i<size; i++)


{
cout << "\n Input student name #" << i+1 <<": ";
getline(cin, stud_name[i]);
cout << "\n Input age: ";
cin >> age[i];
cout << "\n Input student grade: ";
cin>> grade[i];
//to clear one or more characters from the input buffer
cin.ignore(1);
}

12.4 Asking the User to Enter the Size of Array

You can ask the user to enter the exact or estimated size of the array.

// get array size


int size = 0;
cout << “Please enter size of array: “;
cin >> size;
int memberAge[size] = {0};

if this won’t work with your compiler try this format:

data_type *arrayName = new data_type[size];

// get array size


int size = 0;
cout << “Please enter size of array: “;
cin >> size;
int *memberAge = new int[size];

Getting the sum and average of an array

// getiing sum and average

// declare variable to get the total


int sumAge=0, aveAge=0;

// variable to hold average


float sumGrade=0.0, aveGrade=0.0;

103
Array

for (i=0; i<size; i++)


{
sumAge += age[i];
sumGrade += grade[i];
}
aveAge = sumAge/size;
aveGrade = sumGrade/size;
cout << "\n\n Average age of students: " << aveAge;
cout << "\n\n Average grade of students: " << aveGrade;

12.6 Finding the highest and lowest value

// finding highest and lowest value


// assuming all grades are unique
// make the first element the lowest and the highest value

float highGrade = grade[0];


float lowGrade = grade[0];
string studHigh = stud_name[0];
string studLow = stud_name[0];

for(i=1; i<size; i++)


{
// determine if value higher than previous
if (grade[i] > highGrade)
{
highGrade = grade[i];
studHigh = stud_name[i];
}
// determine if value lower than the previous
if (grade[i] < lowGrade)
{
lowGrade = grade[i];
studLow = stud_name[i];
}
}
cout << "\n\n Student with highetst grade: " << studHigh << " -
" << highGrade;
cout << "\n\n Student with lowest grade: " << studLow << " -
" << lowGrade;

104
Array

12.7 Counting – based on the criteria count how many in the array met the criteria.

// counting how namy passed or failed?

int passed=0, failed=0;

for (i=0; i< size; i++)


{
if (grade[i] >= 75)
passed++;
else
failed++;
}
cout << "\n\n PASSED: " << passed;
cout << " \n FAILED: " << failed;

12.7 Searching an array – finding data that match the given requirement.

// print names of students who failed the subject

for (i=0; i<size; i++)


{
if (grade[i] < 75)
cout << stud_name[i] << ”-“ << grade[i] << endl;
}

Sorting – arranging data in ascending or descending order.

Note: Declare variable/s of same data type with the array to hold the data temporarily
when swapping the values. For ascending order, use > in the if statement and < for descending
order.

There are different methods of sorting data, one is Bubble Sorting, It is the simplest sorting
algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.

// An optimized version of Bubble Sort

int j;
int holdAge=0;
float holdGrade=0.0;
string holdName = " ";
bool swapped;

105
Array

for (i = 0; i < size-1; i++)


{
swapped = false;
for (j = 0; j < size-i-1; j++)
{
if (grade[j] < grade[j+1])
{
// do swapping
holdName= stud_name[j];
stud_name[j] = stud_name[j+1];
stud_name[j+1] = holdName;

holdAge= age[j];
age[j] = age[j+1];
age[j+1] = holdAge;

holdGrade= grade[j];
grade[j] = grade[j+1];
grade[j+1] = holdGrade;

swapped = true;
}
}

// IF NO two elements were swapped by inner loop, then break

if (swapped == false)
break;
}

cout <<"\n\n Student List ";


cout <<"\n\n Name\t\t Age\t\t Grade\n\n" ;
for (i=0; i < size; i++)
cout << i+1 << ". " << stud_name[i] << "\t\t" << age[i] << "\t\t"
<< grade[i] << endl;

106
Array

Activities

A. Write an array declaration that will store the following data:

1. 50 letter grades
2. commissions of ten salesmen
3. daily temperature in Celsius for the month of August
4. number of population of each region in the Philippines
5. names of 50 students

B. Write a program segment for the following:

1. count how many A letter grades in array # A 1


2. Get the average commission in array #A2
3. Display the day with highest and lowest temperature in array #A3
4. Display name of region with population more than 1 million
5. Display the names of students in alphabetical order

Programming

One-dim Array

1. Write a program that will ask the user to enter a name and then display the letters that
appeared more than once and the number of their occurrence.

Enter a name: Elyse Raina Villanueva


a - 4
e - 3
i - 2
l - 3
n - 2
v - 2

2. Profiling of Customer – write a C++program that will store the profile of 15 customers in
arrays. Input the name of the customer, gender (F and M only) and the age. After
inputting the data, display the following information – how many are male, how many are
female, how many are minors (less than 18years old), senior (60 years and above) and
adults (those that were not considered as minor and senior).

107
Array

Profiling of Customer

Input:

Name:_____
Gender(M or F):____
Age( in number):____

Output:

# of Male Customer:___
# of Female Customer:___
Minor s(Less than 18 years old):___
Adults(19-59 years old):____
Seniors(60 and above): _____

3. Monthly Household Expense – Create arrays (size 15) that will hold the following
information: category and amount). Allow the user to enter the category (ex. Water bill)
and the corresponding amount spent on it. After the data entry, display the household
categories and its corresponding amount in descending order (highest amount first) and
the total amount spent in a month.

Monthly Household Expense

Enter Category #1:___


Amount Spent:___

Enter Category #2:___


Amount Spent:____
:
Enter Category #15:___
Amount Spent:___

Category Amount
______ ______

______ ______

: :

______ ______

Total: ______

108
Array

4. There are 15 candidates for the position of Barangay Captain. Using an array, write a
program that will ask the user to enter the names of the candidate and the total votes
he/she received. After the data entry, display the data in descending order based on the
votes of the candidates. Compute and display also the total votes cast for this election.

Online References

https://beginnersbook.com/2014/01/c-arrays-example/

https://www.geeksforgeeks.org/arrays-in-c-cpp/

https://www.tutorialspoint.com/cplusplus/cpp_arrays.htm

109
Functions

UNIT 13 : Functions

Introduction

Any C program always starts with the main() function. It is the only function that can start
automatically while others are needed to be called. Function is a block of codes that performs a
specific task. You can pass data (parameters) to and from a function.

C++ provides many pre-defined functions that we can use, but there are times that a
programmer must create their own functions that will cater to the requirements of the system or
program (user-defined function). Functions can be called several times. It also makes our
program modular – you can divide your program into several functions that makes program
easy to understand, modify and debug.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Declare and define functions


2. Apply how to pass data to and from functions in your programs
3. Create different types of functions.
4. Use basic pre-defined mathematical functions in math/engineering programs

Course Materials

There are two types of function

1. Pre-defined or Standard Library Function. The library functions are declared in header
files and defined in library files.

2. User-defined Function. Created by the user.

( For this lesson we will focus mainly on the user-defined function.)

For functions to be executed they must be called by main() or other functions that may need
them. But before we can use a function they must be first declared before the main() program.
We can declare and define the function at the same time or we can also do it separately. We
must also limit our function in performing just one task, to make it reusable.

110
Functions

Example 1:

#include <iostream>
using namespace std;

int max(int x, int y) function declaration


{
if (x > y)
return x;
else function definition
return y;
}

int main() {
int a = 0, b = 0, m=0;

cout << "Enter an integer: ";


cin >> a;
cout << "Enter another integer: ";
cin >> b;

// Calling above function to find max of a and b


m = max(a, b);

cout << endl << m << " is higher.";


return 0;
}

Example 2:

#include <iostream>
using namespace std;

int max(int x, int y); function declaration (w/o the body)

int main() {
int a = 0, b = 0, m=0;

cout << "Enter an integer: ";


cin >> a;
cout << "Enter another integer: ";
cin >> b;

// Calling above function to find max of a and b


m = max(a, b);

111
Functions

cout << endl << m << " is higher.";


return 0;
}

int max(int x, int y)


{
if (x > y)
return x;
else function definition
return y;
}

Both programs will yield the same output. Example1, declares and defines the function
at the same time, while Example 2, declares and defines the function separately.

Enter an integer: 89
Enter another integer: 56

89 is higher.

You will often see C++ programs that have function declaration before main(), and
function definition after main(). This will make the code better organized and easier to read

13.1 Function Declaration and Function Calling

A function declaration tells the compiler how many parameters (data) a function takes,
the data-types of parameters and return type of function. Function name must also follow the
rules in giving Identifiers. The function definition is the body of the function.

Syntax:

return-type FunctionName ( parameter1, parameter2,…)


{
//body of function;
}

112
Functions

Return-type
Function name

Formal Parameters , enclosed in ()


int max(int x, int y)
{
if (x > y)
return x; Body of the function
else enclosed in {}
return y;
}

In this example, there are two parameters, both of them are integers. We have to define
the data type of each parameter, (int x, y) is not allowed. The numbers of parameters must
match with the actual number of values passed to the function. In the main program we have
this line, m = max(a, b); that calls for the function max to execute and the value returned by
the function will be stored in variable m.

// function calling
m = max(a, b);

Actual Parameters or arguments enclosed in ()

Name of function to be called

a and b are the actual values to be passed. So, a will be x in the function and b will be
y. In the main() function, a and b was declared as int, so in the max function the receiving
parameter must have the same data-type.

max is the name of the function. Again, C language is case sensitive so max is not the
same as MAX or Max.

This function will return a value to the main(), that is why there is an int before the
function name max. The receiving variable (m) in the main() must have the same data-type with
the return-type. If no value will be returned to main() we just put the word void in the return-
type.

The body of the function is enclosed in a pair of {}. You can use any statement inside it.
A function can also call another function. You can also declare variables inside a function but
their use is exclusive only inside that function (local variable).

113
Functions

13.2 Function Prototype

Syntax:

return-type FunctionName( data-type1, data-type2,…);

If you like to separate the function declaration and function definition, you can just type
the function prototype before main(). With the prototype, you don’t need to put the formal
parameter names, just their data types separated by commas and there is a semicolon at the
end.

#include <iostream>
using namespace std;

int max(int, int); // function prototype

int main() {
int a = 0, b = 0, m=0;

cout << "Enter an integer: ";


cin >> a;
cout << "Enter another integer: ";
cin >> b;

// Calling above function to find max of a and b


m = max(a, b);

cout << endl << m << " is higher.";


return 0;
}

int max(int x, int y)


{
if (x > y)
return x;
else
return y;
}

Note: The type of the arguments passed while calling the function must match with the
corresponding parameters defined in the function declaration.

114
Functions

13.3 Types of User-defined Function

1. Function that returns a value


2. Void functions
a. No value passed
b. Pass by value
c. Pass by reference

13.3.1 Function that Returns a Value

This type of function, as shown in the previous examples, returns only one value to the
calling function. You specify the type of data to be returned before the function name and it must
match with the data type of the receiving variable. A return value; statement must be
issued before exiting the function.

Value can be a variable, or a constant value or an expression.

Examples:
return x;
return 10;
return (a+b)/2;

Example: returns a value

#include <iostream>
using namespace std;

int inputData(void);
int ifEven(int);

int main()
{
int num=0,even=0;

num=inputData(); // no value was passed


even = ifEven(num);
if (even)
cout << endl << num << " is an even number.";
else
cout << endl << num << " is an odd number.";
return 0;
}

115
Functions

int inputData(void)
{
int n=0; //local variable

cout << "Enter an integer: ";


cin >> n;
return n;
}

int ifEven(int n)
{
if (n%2 == 0)
return 1;
else
return 0;
}

13.3.2 Void Function – No value Passed

When no value shall be returned to the calling function, we type void in the return-type
of the function header. Likewise, if no value/argument will be passed to the function being called
we also type void inside the () or we can just leave it blank.

Example : no value/arguments passed and no return value

#include <iostream>
using namespace std;

void addition(void); //function prototype

int main()
{
//add two values
addition(); //function call
cout<< "\n\nDONE";
}

void addition(void)
{
int n1,n2; //local variables

cout << "\n Addition of two numbers\n\n";


cout << " Enter first integer: ";
cin >> n1;
cout <<"\n\n Enter 2nd integer: ";
cin >> n2;
cout << "\n\n Sum = " << n1+n2;
}

116
Functions

13.3.3 Void Function – Pass by Value

In this parameter passing method, values of actual parameters are copied to function’s
formal parameters and the two types of parameters are stored in different memory locations. So
any changes made inside functions are not reflected in actual parameters of caller.

Example 1: values were passed to addition function but no value was returned to main()

#include <iostream>
using namespace std;

void addition(int,int);

int main()
{
int n1,n2;
cout << "\n Addition of two numbers\n\n";
cout << " Enter first integer: ";
cin >> n1;
cout <<"\n\n Enter 2nd integer: ";
cin >> n2;
addition(n1,n2);
cout<< "\n\n DONE";
}

void addition(int N1, int N2)


{
int sum;
sum = N1 + N2;
cout << "\n\n Sum = " << sum;
}

main()
45 64
n1 n2
addition()
45 64 109
N1 N2 sum

Computer Memory

117
Functions

13.3.4 Void Function – Pass by Reference

Both actual and formal parameters refer to same locations, so any changes made inside
the function are actually reflected in actual parameters of caller. We used an ampersand (&)
before the formal parameter when we want to pass by reference.

In the example program below, we input the values for n1 and n2 in the function addition.
The value received by N1 and N2 will also be the value of n1 and n2 respectively since they
occupy the same memory location.

#include <iostream>
using namespace std;

void addition(int &,int &);

int main()
{
int n1,n2,sum;
addition(n1,n2);
sum = n1 + n2;
cout << "\n\n Sum = " << sum;
cout<< "\n\n DONE";
}

void addition(int &N1, int &N2)


{
cout << "\n Addition of two numbers\n\n";
cout << " Enter first integer: ";
cin >> N1;
cout <<"\n\n Enter 2nd integer: ";
cin >> N2;
}

45 64 109
main() n1 n2 sum
addition() &N1 &N2

Computer Memory

118
Functions

We can also have a function that can pass by value and pass by reference at the same
time.

Example:

#include <iostream>
using namespace std;

void addition(int ,int, int & );

int main()
{
int n1,n2,sum;
cout << "\n Addition of two numbers\n\n";
cout << " Enter first integer: ";
cin >> n1;
cout <<"\n\n Enter 2nd integer: ";
cin >> n2;
addition(n1,n2,sum);
cout << "\n\n Sum = " << sum;
cout<< "\n\n DONE";
}

void addition(int N1, int N2, int &SUM)


{
SUM = N1 + N2;
}

13.4 Function Calling Another Function

In this example, a function - not main() will call another function.

Example:

#include<iostream>
using namespace std;

//compute the average

void inputValues(int ENTRYS, int &TOTAL);


void Entries (void);

119
Functions

int main()
{
Entries();
return 0;
}

void inputValues(int ENTRYS, int &TOTAL)


{
int i,no;
cout <<"\nInput values:\n";
for (i =1; i<=ENTRYS; i++)
{ cout << endl << i << ". ";
cin >> no;
TOTAL=TOTAL+no;
}
}

void Entries (void)


{
int entries=0,total=0, average=0;
cout << "Input how many numbers to average? ";
cin >> entries;
inputValues(entries, total); // call another function
average = total/entries;
cout << "\n\nAverage: " << average;
}

120
Functions

13.5 Passing Array to Function

When passing the whole array to a function, only the name of the array is used in the
function call. The whole array is always passed by reference no need to include the & before
the formal parameter.

Example:

# include <iostream>
# include <string>

using namespace std;

void Entries(int size, string [], int [], float []);

int main()
{
int i, size=3;
string stud_name[3] = {" "};
int age[3] = {0};
float grade[3] = {0.0};

// input data
Entries(size, stud_name, age, grade);

// getiing sum and average


int sumAge=0, aveAge=0;
float sumGrade=0.0, aveGrade=0.0;

for (i=0; i<size; i++)


{
sumAge += age[i];
sumGrade += grade[i];
}
aveAge = sumAge/size;
aveGrade = sumGrade/size;
cout << "\n\n Average age of students: " << aveAge;
cout << "\n Average grade of students: " << aveGrade;

return 0;
}

121
Functions

void Entries(int size, string names[], int ages[], float grades[])


{
for(int i=0; i<size; i++)
{
cout << "\n Input student name #" << i+1 <<": ";
getline(cin, names[i]);
cout << "\n Input age: ";
cin >> ages[i];
cout << "\n Input student grade: ";
cin>> grades[i];
cin.ignore();
}
}

Note: no need to specify the size of array in the function header.

If you want to pass specific element of an array is to a function:

Array: float grade[10];

Function header: return-type functionName( float score)

Function call: functionName(grade[i]);


functionName(grade[5]);

122
Functions

13.6 Recursive Function

A function that calls itself is known as recursive function. This


his method or technique is
known as recursion.

The recursion continues until some condition is satisfied. To avoid


oid infinite recursion, an
if statement or other conditional approach must be use to make the recursive call or to exit the
function.

https://www.programiz.com/cpp-
The following text and samples were taken from https://www.programiz.com/cpp
programming/recursion

Working of Recursion in C++

void recurse()
{
... .. ...
recurse();
... .. ...
}

int main()
{
... .. ...
recurse();
... .. ...
}

The figure below shows how recursion works by calling itself over and over again.

123
Functions

Example 1: Factorial of a Number Using Recursion

// Factorial of n = 1*2*3*...*n

#include <iostream>
using namespace std;

int factorial(int);

int main() {
int n, result;

cout << "Enter a non-negative number: ";


cin >> n;

result = factorial(n);
cout << "Factorial of " << n << " = " << result;
return 0;
}

int factorial(int n) {
if (n > 1) {
return n * factorial(n - 1);
} else {
return 1;
}
}

Output

Enter a non-negative number: 4


Factorial of 4 = 24

124
Functions

Working of Factorial Program

How this C++ recursion program works

125
Functions

The following is lifted from https://www.geeksforgeeks.org/c-mathematical-functions/

13.7 C++ Mathematical Functions

C++ being superset of C, supports large number of useful mathematical functions. These
functions are available in standard C++ and C to support various mathematical calculations.
Instead of focusing on implementation, these functions can be directly used to simplify code and
programs. C++ provides large set of mathematical functions which are stated below –
In order to use these functions you need to include header file- <math.h> or <cmath>.

1. double sin(double) : This function takes angle (in degree) as an argument and return its
sine value that could be verified using sine curve.

2. double cos(double) : This function takes angle (in degree) as an argument and return its
cosine value that could be verified using cosine curve.

3. double tan(double) : This function takes angle (in degree) as an argument and return its
tangent value. This could also be verified using Trigonometry as Tan(x) = Sin(x)/Cos(x).

4. double sqrt(double) : This function takes number as an argument and return its square
root value. Number can not be negative value.

5. int abs(int) : This function takes integer number as an argument and return its absolute
value. It means, the output will always be positive regardless of sign of input.

6. double pow(double, double) : This function takes one argument as base and other as
exponent.

7. double hypot(double, double) : This function requires two sides of the right angled
triangle to give output as its hypotenuse.

8. double floor(double) : This functions returns the integer value lesser or equal to
argument passed in the function.

9. double fabs(double) : This function returns the absolute value of any number.

10. double acos(double) : This function returns the arc cosine of argument. The argument to
acos() must be in the range -1 to 1 ; otherwise, a domain error occurs.

11. double asin(double) : This function returns the arc sine of argument. The argument to
asin() must be in the range -1 to 1 ; otherwise, a domain error occurs.

12. double atan(double) : This function returns the arc tangent of arg.

13. double atan2(double, double) : This function returns the arc tangent of (double
a)/(double b).

14. double ceil(double) : This function returns the smallest integer as double not less than
the argument provided.

126
Functions

15. double cosh(double) : This function returns the hyperbolic cosine of argument provided.
The value of argument provided must be in radians.

16. double tanh(double) : This function returns the hyperbolic tangent of argument provided.
The value of argument provided must be in radians.

17. double log(double) : This function takes a number and returns the natural log of that
number.

// C++ program to illustrate some of the


// above mentioned functions

#include <iostream>
#include <math.h>
using namespace std;

int main()
{
double x = 2.3;
cout << "Sine value of x=2.3 : " << sin(x) << endl;
cout << "Cosine value of x=2.3 : " << cos(x) << endl;
cout << "Tangent value of x=2.3 : " << tan(x) << endl;

double y = 0.25;
cout << "Square root value of y=0.25 : " << sqrt(y) << endl;

int z = -10;
cout << "Absolute value of z=-10 : " << abs(z) << endl;
cout << "Power value: x^y = (2.3^0.25) : " << pow(x, y) << endl;

x = 3.0;
y = 4.0;
cout << "Hypotenuse having other two sides as x=3.0 and"
<< " y=4.0 : " << hypot(x, y) << endl;

x = 4.56;
cout << "Floor value of x=4.56 is : " << floor(x) << endl;

x = -4.57;
cout << "Absolute value of x=-4.57 is : " << fabs(x) << endl;

x = 1.0;
cout << "Arc Cosine value of x=1.0 : " << acos(x) << endl;
cout << "Arc Sine value of x=1.0 : " << asin(x) << endl;
cout << "Arc Tangent value of x=1.0 : " << atan(x) << endl;

127
Functions

y = 12.3;
cout << "Ceiling value of y=12.3 : " << ceil(y) << endl;

x = 57.3; // in degrees
cout << "Hyperbolic Cosine of x=57.3 : " << cosh(x) << endl;
cout << "Hyperbolic tangent of x=57.3 : " << tanh(x) << endl;

y = 100.0;
// Natural base with 'e'
cout << "Log value of y=100.0 is : " << log(y) << endl;

return 0;
}
Output:
Sine value of x=2.3 : 0.745705
Cosine value of x=2.3 : -0.666276
Tangent value of x=2.3 : -1.11921
Square root value of y=0.25 : 0.5
Absolute value of z=-10 : 10
Power value: x^y = (2.3^0.25) : 1.23149
Hypotenuse having other two sides as x=3.0 and y=4.0 : 5
Floor value of x=4.56 is : 4
Absolute value of x=-4.57 is : 4.57
Arc Cosine value of x=1.0 : 0
Arc Sine value of x=1.0 : 1.5708
Arc Tangent value of x=1.0 : 0.785398
Ceiling value of y=12.3 : 13
Hyperbolic Cosine of x=57.3 : 3.83746e+24
Hyperbolic tangent of x=57.3 : 1
Log value of y=100.0 is : 4.60517

128
Functions

Activities

Write appropriate function declaration or call for the following situation:

1. a function call that will pass two integer variables


__________________________________________________________________
2. a function call that will pass the actual values of two float, an integer and a character
__________________________________________________________________
3. a function call that will pass the content of array BOOKS
__________________________________________________________________
4. a function declaration that will return a character and will receive the values of an integer
variable and the address of a float variable from main()
__________________________________________________________________
5. a function declaration that will receive the address of two integer variables and the value
of the fifth element of array STUDENTS
__________________________________________________________________

Determine the output of the following program:

1.
# include <iostream>
using namespace std;

int subtraction ( int a, int b )


{
int r;
r = a - b;
return r;
}

int main()
{
int x = 5, y = 3, z;

z = subtraction( 7, 2 );
cout << "The first result is " << z << endl;
cout << "The second result is " << subtraction(2,7) << endl;
cout << "The third result is " << subtraction(x,y) << endl;
z = 4 + subtraction(x,y);
cout << "The final result is " << z << endl;
return 0;
}

129
Functions

2.
# include <iostream>
using namespace std;

void duplicate (int &a, int &b, int &c)


{
a *= 2;
b *= 2;
c *= 2;
}

int main()
{
int x = 1, y = 3, z = 7;

duplicate(x, y, z);
cout << "x = " << x << ", y = " << y << ", z =" << z;
return 0;
}

3.
#include <iostream>
using namespace std;

void prevnext (int x, int &prev, int &next)


{
prev = x - 1;
next = x + 1;
}

int main()
{
int x = 100, y, z;
prevnext(x, y, z);
cout << "x is " << x << endl;
cout << "Previous = " << y << ", Next = " << z;
return 0;
}

Programming Exercises

1. Create a program that will use three value-returning functions (main, getName and
getSalary) and four void functions (calcFwt, CalcFica, and calcNetPay – pass by
reference and displayInfo – pass by value). The program will ask the user to input the

130
Functions

name and weekly salary of an employee. Calculate the federal withholding tax(FWT) by
multiplying the weekly salary by the FWT rate of 20% and the federal insurance
contribution act (FICA)by multiplying the weekly salary by the FICA rate of 8% .
Calculate the weekly net pay by subtracting the FWT and FICA from the weekly salary.
Display the name, FWT, FICA and weekly net pay.

2. There are 15 candidates for the position of Barangay Captain. Using an array, write a
program that will ask the user to enter the names of the candidate and the total votes
he/she received. After the data entry, display the data in descending order based on the
votes of the candidates. Also, compute and display the total votes cast for this election.
Make use of different functions to this program.

3. Write a program using functions to solve the problem below: (use 2 value returning
functions and 2 void functions)

Input the following data:

Name of patient
Age of patient
Philhealth member [y/n]
Total hospital bill in pesos

Compute the amount to be paid by the patient based on the following conditions:

- If Philhealth member deduct 15% from the total hospital bill


- If senior citizen deduct 20% after deducting Philhealth discount
- No discount if not senior or not member of Philhealth

Online References

https://www.tutorialspoint.com/cplusplus/cpp_functions.htm

https://www.programiz.com/cpp-programming/function

https://www.geeksforgeeks.org/functions-in-c/

https://www.studytonight.com/cpp/functions-in-cpp.php

131
String Manipulation

UNIT 14: String Manipulation

Introduction

String is actually a one-dimensional array of characters which is terminated by


a null character '\0'. When the compiler encounters a sequence of characters enclosed in the
double quotation marks, it appends a null character \0 at the end by default.

In C++, string data type is used for declaring string variable that can contain a
collection of characters surrounded by double quotes.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Differentiate the two types of string commonly used in C++.


2. Explain the use of each string function.
3. Use the most commonly used string functions to control strings.

Course Materials

In C++, we can store string in two different ways:

1. C-style Strings (still supported by C++)


2. String class (this will be further discuss)

14.1 C-Style String – are actually an array of type char terminated by a null character ‘ \0’.

Examples:

char name[6] =”Raina”;


char name[] =”Raina”;
char name[6] = {‘R’, ’a’ ,’I’ ,’n’ ,’a’ ,’\0’};
char name[] = {‘R’, ’a’ ,’I’ ,’n’ ,’a’ ,’\0’};

R A i n a \0
name 0 1 2 3 4 5

132
String Manipulation

String Class – internally C++ string class uses char array to store string but all memory
allocation, management, and null termination is handled by string class that is why it is easy to
use. The length of the C++ string can be changed during program execution because of
dynamic allocation of memory. It has no fixed length and can be expanded or reduced
depending on the requirement of the program or user.

Examples:

string school = “PUP Santa Rosa”;


or
string school(“PUP Santa Rosa”);

In his module, we will discuss the string class because it has more functions that are
much easier to use.

14.2 Declare and Initialize String

// declaring only

string str0;

// declaring and initializing with null value

string str0 =””; str0

// initialization by raw string

string str1("PUP Manila"); str1 PUP Manila

// initialization by another string

string str2(str1); str2 PUP Manila

// initialization by character with number of occurrence

string str3(5, '#'); str3 #####

// initialization by part of another string

string str4(str1, 4, 6); // from 4th index (second parameter)

// 6 characters (third parameter) str4 Manila

// initialization by part of another string : iterator version

string str5(str2.begin(), str2.begin() + 3); str5 PUP

133
String Manipulation

Assignment Operator ( = )

string name, studName;


:
name = “Juan dela Cruz”;
studName = name;

Other String Functions

1. clear() - deletes all character from string

name.clear();

2. size() and length() – return the length of a string

int len = studName.length();


// same as int len = studName.size();
cout << "Length of string is : " << len << endl;

3. [] operator – to access a particular character

char ch = studName.at(2); // same as ch = studName[2];


cout << "third character of string is : " << ch << endl;

char ch_f = studName[0];


char ch_b = sttudName[studName.length() - 1]
cout << "First char is : " << ch_f << ", Last char is : "
<< ch_b << endl;

4. append() – add the argument string at the end

studName.append(" Jr."); // same as studName += " Jr.";

// another version of append, which appends part of other string

string salutation = “Mr. ”;

// insert salutation at 0th position of studName and add


// len characters of studNsme
salutation.append(studName, 0, len);

cout << salutation << endl; // Mr. Juan dela Cruz Jr.
cout << studName << endl; // Juan dela Cruz Jr.

134
String Manipulation

5. find() - find returns index where pattern is found. If pattern is not there it returns
predefined constant npos whose value is -1

string address = “879 M. Gonzaga St. Mandaluyong City”;


string city = “San Juan”;
if (address.find(city) != string::npos)

cout << city << “ found in “ << address <<” at " <<
address.find(city) << " pos" << endl;
else
cout << city <<” not found in " << address << endl;

6. substr(a, b) - returns a substring of b length

// starting from index a

cout << address.substr(0, 3) << endl;

// if second argument is not passed, string till end


// is taken as substring

cout << address.substr(4) << endl;

7. erase(a, b) - deletes b characters at index a

address.erase(0, 4);
cout << address << endl;

8. replace(a,b,str) – replaces b characters from index a by str

address.replace(0, 3, "123”);
cout << address << endl;

9. transform() – controls the case of a string. Converts letter to uppercase or lowercase

transform(stringVar.begin(), stringVar.end(), stringVar.begin(),:: function);

function is either toupper or tolower

needs #include<algorithm> at the beginning of the program

transform(address.begin(),address.end(),address.begin(),::toupper);
cout << address;

135
String Manipulation

10. compare() – compares a portion of a string to another string.

string1.compare(index, number of characters to compare, string2);

returns 0 if true if match, -1 if no match

int x=0;
string celNo=”09178880099”;
string net =”0917”;
x= celNo.compare(0, 4, net);
if (x==0)
cout << “Globe Number!”;
else
cout <<”Other network number.”;

11. assign() – assigns a portion of a string variable to another string variable.

destinationStr.assign(sourceStr, startPos, noOfStrToGet);

string empNo = “234512”;


string dept = “ “;
dept.assign(empNo,4,2);
cout << “Employee Number: “ << empNo << endl;
cout << “Department Code: “ << dept <<endl;

assign() is also used to duplicate a character

stringVar.assign(numberOfTimes, character);

char letter;
string letterRepeat="";
cout << "Enter a character to repeat: ";
cin >> letter;
cout << "How many times to repeat? ";
cin >> x;
letterRepeat.assign(x,letter);
cout << endl << letterRepeat;

12. Concatenating string (+)

string first,last,full;
cin.ignore();
cout <<"Enter last name: ";
getline(cin,last);
cout <<"Enter first name: ";

136
String Manipulation

getline(cin,first);
full=last + ", " + first;
cout << endl << full;

// C++ program to demonstrate various function string class

#include<iostream>
#include<algorithm>

using namespace std;

int main()
{
// various constructor of string class
string str0="\0";

// initialization by raw string


string str1("PUP Manila");

// initialization by another string


string str2(str1);

// initialization by character with number of occurrence


string str3(5, '#');

// initialization by part of another string


string str4(str1, 4, 6); // from 4th index (second parameter)
// 6 characters (third parameter)

// initialization by part of another string : iteartor version


string str5(str2.begin(), str2.begin() + 3);

cout << "str0 = " << str0 << endl;


cout << "str1 = " << str1 << endl;
cout << "str2 = str1 " << str2 << endl;
cout << "str3(5, '#') " << str3 << endl;
cout << "str4(str1, 4, 6) " << str4 << endl;
cout << "str5(str2.begin(), str2.begin() + 3) " << str5 << endl;

// assignment operator
cout << "\n Assignment Operator = \n\n";
string str6 = str4;
cout << "str6 = str4: "<< str6 << endl << endl;
system("pause");

// length of string
cout << "\n Get the length or size of a string \n\n";

137
String Manipulation

string studName, name = "Juan dela Cruz";


studName = name;
cout << "studName = " << studName << endl;
int len = studName.length();
// same as int len = studName.size();
cout << "\nLength of string is : " << len << endl << endl;
system("pause");

//get a character from a string


cout <<"\n Get a character from a string\n\n";
char ch = studName.at(2);
// same as ch = studName[2];
cout << "third character of string is : " << ch << endl;

char ch_f = studName[0];


char ch_b = studName[studName.length() - 1];
cout << "First char is : " << ch_f << ", Last char is : " << ch_b << endl << endl;
system("pause");

//studName.append(" Jr.");
cout <<"\n Add something on the string\n\n";
studName += " Jr." ;
cout << studName << endl;

//append
len = studName.length();
string salutation = "Mr. ";
salutation.append(studName, 0, len); // at 0th position 3 characters
cout << salutation << endl;
cout << studName << endl << endl;
system("pause");

//find
cout <<"\n Find a string within a string\n\n";
string address = "879 M. Gonzaga St. Mandaluyong City";
string city = "Mandaluyong";
cout << "address = 879 M. Gonzaga St. Mandaluyong City " << endl;
if (address.find(city) != -1)
cout << city << " found in " << address <<" at " << address.find(city) << " pos" << endl << endl;
else

cout << city <<" not found in " << address << endl << endl;
system("pause");

// replace
cout << "\n Replace a portion of a string\n\n";
address.replace(0, 3,"123");
cout << address << endl << endl;
system("pause");

138
String Manipulation

//erase
cout <<"\n Erase a portion of a string\n\n";
address.erase(0, 4);
cout << address << endl << endl;
system("pause");

// controlling the case of a string


cout <<"\n Converts the string to all capital letters\n\n";
transform(address.begin(),address.end(),address.begin(),::toupper); // needs #include,algorithm.
cout << address << endl << endl;
system("pause");

// compare
cout <<"\n Compares a portion of a string to another string\n\n";
int x=0;
string celNo="09178880099";
string net ="0917";
cout << celNo << endl;
x= celNo.compare(0, 4, net);
if (x==0)
cout << "Globe Number!" << endl << endl;
else
cout <<"Other network number." << endl <<endl;
system("pause");

// assign
cout <<"\n Assign a portion of a s string to another string variable\n\n";
string empNo = "234512";
string dept = " ";
dept.assign(empNo,4,2);
cout << "Employee Number: " << empNo << endl;
cout << "Department Code: " << dept << endl << endl ;
system("pause");

//duplicate a character and assign it to a string variable


cout << "\n Display a character repeatedly\n\n";
char letter;
string letterRepeat="";
cout << "Enter a character to repeat: ";
cin >> letter;
cout << "How many times to repeat? ";
cin >> x;
letterRepeat.assign(x,letter);
cout << endl << letterRepeat<< endl << endl;
system("pause");

//concatenation
cout <<"\n Concatenating Strings\n\n";

139
String Manipulation

string first,last,full;
cin.ignore();
cout <<"Enter last name: ";
getline(cin,last);
cout <<"Enter first name: ";
getline(cin,first);
full=last + ", " + first;
cout << endl << full << endl <<endl;
system("pause");

return 0;
}

140
String Manipulation

141
String Manipulation

Activities:

Write appropriate C++ statements using string function to perform the following:

1. converts the contents of a string variable name employee to uppercase

2. determines if the code variable contains either ‘X’ or ’x’. use tolower function in the if
clause

3. determine if the variable subject contains five characters

4. concatenated the open parenthesis, the content of areaCode variable and the close
parenthesis, and then store the result in displayAreaCode variable

5. replace the two characters located in positions 4 and 5 in a string variable named
subjectCode with “CS”

6. converts the contents of studName variable to all capital letters

7. determine if the mobile phone number entered in celNo was complete (11 digits)

8. compare the first two characters in empNumber to “29”

142
String Manipulation

9. determine if there is “MANILA” in the value stored in address variable

10. get the 3rd and 4th character in variable employNumber and assign it to deptCode

Programming

Write a program that will input the following data:

- First name
- Last name
- Middle name
- Student number format: yyyy-ddddd-cc-d
o yyyy is year ex. 2020
o ddddd are any digit from ‘0’ to ‘9’
o cc are characters from ‘A’ to ‘Z’ that stands for the campus code ex. SR
o d is any digit from ‘0’ to ‘9’
- course code ex. BSIT, BSECE, BSA

Convert all data in capital letters

Validate student number based on the format given. Ask user to enter another value if
previously entered was invalid.

Find how many students are eligible to become DOST scholar and how many are residents
of LAGUNA.

To be a DOST scholars your course must be either BSIT, BSIE or BSECE and belong to
batch 2020.

Example Screen Display

Input Last name: Castro


First name: Nancy
Middle name:_Dela Rosa

Address: 24-B Maybunga St. Brgy. Mabait, Calamba, Laguna

Student Number: 2020-ab123-sr-0

Invalid Entry! Please enter another value.

143
String Manipulation

Student Number: 2020-00123-sr-0

Course Code: BSIT

CONGRATULATIONS! You are eligible to apply as a DOST scholar.

More entry [Y/N] ? Y

Input Last name: Mendoza


First name: Ocean
Middle name: Vasquez

Address: B29 L36 New York St. Green State Subd. Brgy. Ibaba, Carmona, Cavite

Student Number: 2020-00234-sr-0

Course Code: BSHRM

More entry [Y/N] ? N

Total number of students eligible for DOST scholarship: ____


Total number of students from LAGUNA: ____

Online References

https://www.tutorialspoint.com/cplusplus/cpp_strings.htm

https://www.w3schools.com/cpp/cpp_strings.asp

https://www.geeksforgeeks.org/c-string-class-and-its-applications/

144
Pointers

UNIT 15: Pointers

Introduction

Pointer is one of the most important features of C programming language. Pointer


allows us to manipulate data directly by using their address in the computer’s memory. When
we declare a variable that holds data we give it a name but we really don’t know where in the
memory they reside. We can use pointers to know the address of these variables. Pointers can
also reduce our code and improve the performance of our program.

A pointer is also a variable that holds the address of another variable. It also has a data
type, if the pointer will hold the address of an integer variable then the pointer’s data type should
also be an integer. Like any other variables and constants, pointers must be declared and
initialized before they can be used.

https://simplesnippets.tech/cpp-pointers-concept-with-example/

This module will discuss only the basics about pointers and some of its applications.
Further discussion on pointer will be discussed in Programming 2 and Data Structure subjects.

Learning Objectives:

After successful completion of this lesson, you should be able to:

1. Know the importance of pointers in programming


2. Know how to manipulate pointers and use them in your program
3. Write programs using pointers.

145
Pointers

Course Materials

Just like any variable or constant, we have to declare pointers before we can use them.
Pointer will store the address of the variable or constant that it points to. Their actual content
whether they point to an int, char, double or float is a hexadecimal number that represents an
address which is 2 bytes.

15.1 Pointer Declaration

Syntax:

data-type *pointerVariableName;

data-type is the type of data that it will point (int, float, double, char ….)

The * (asterisk) denotes that it is a pointer variable

pointerVariableName define by the user (follow the rules in giving identifiers)

Examples:

int *intPt; // pointer to an integer


double *doPt; // pointer to a double
float *flPt; // pointer to a float
char *chPt // pointer to character

15.2 Reference operator (&) and Deference operator (*)

Reference operator (&) - gives the address of a variable.


Dereference operator (*) - gives the value stored in the memory address.

For example:

If an integer variable is stored in the memory address 0x6dfed4, and it contains a


value 15.
The reference (&) operator gives the value 0x6dfed4, while the dereference
(*) operator gives the value 15.

To point a pointer to a variable

pointerVariableName = &variableName

To change the value of the pointer

*pointerVariableName = value;

146
Pointers

Example Program:

# include <iostream>
using namespace std;

int main()
{
string school ="PUP Santa Rosa";
string* schPtr = NULL; // pointer points to nothing

// assigns the address of variable school to pointer variable schPTR


schPtr = &school;
cout << "string school =\"PUP Santa Rosa\";";
cout << "\n\nEffect of schPtr = &school";
cout << "\n\n Value stored in variable school: " << school;
cout << "\n\nMemory Address of variable school: " << &school;
cout << "\n\n Value pointed by schPtr: " << *schPtr;
cout << "\n\n Value stored in schPtr: " << schPtr;
cout << "\n\nMemory Address of pointer variable schPtr: " << &schPtr;
cout << "\n\n=========================================================";
// assigns another value to school using pointer
*schPtr = "PUP Manila";
cout << "\n\nEffect of *schPtr =\"PUP Manila\" ";
cout << "\n\n Value stored in variable school: " << school;
cout << "\n\nMemory Address of variable school: " << &school;
cout << "\n\n Value pointed by schPtr: " << *schPtr;
cout << "\n\n Value stored in schPtr: " << schPtr;
cout << "\n\nMemory Address of pointer variable schPtr: " << &schPtr;
return 0;
}

147
Pointers

15.3 Pointers in C++


The following are the concepts and description of pointers in C++ that a programmer must be
familiar with:
Source: https://www.tutorialspoint.com/cplusplus/cpp_pointers.htm

Sr.No Concept & Description

1 Null Pointers

C++ supports null pointer, which is a constant with a value of zero defined in several
standard libraries.

2 Pointer Arithmetic

There are four arithmetic operators that can be used on pointers: ++, --, +, -

3 Pointers vs Arrays

There is a close relationship between pointers and arrays.

4 Array of Pointers

You can define arrays to hold a number of pointers.

5 Pointer to Pointer

C++ allows you to have pointer on a pointer and so on.

6 Passing Pointers to Functions

Passing an argument by reference or by address both enable the passed argument to be


changed in the calling function by the called function.

7 Return Pointer from Functions

C++ allows a function to return a pointer to local variable, static variable and dynamically
allocated memory as well.

For further explanation and sample programs for each concepts please visit the site.

148
Pointers

The program below is an application of concepts 1-3

//pointers and arrays

int main()
{
float grades[5]= {0.0};
float* grdPtr =NULL;

grdPtr = grades; //points to the first element of the array

for(int i=0; i< 5; i++)


{
cout << "Input grade: ";
cin >> grades[i];
}

// prints the contents of array using pointer

cout <<"\n\nThe following grades were entered: \n";


for (int i=0;i<5;i++)
{
cout << endl << *grdPtr; // print value pointed by grdPtr
grdPtr++; // moves the pointer to the next element of the array
}
return 0;
}

Note: The highlighted lines can be replaced with: cout << endl << *(grdPtr+i);

149
Pointers

Example with some arithmetic operation:

#include<iostream>
using namespace std;

//pointers and arrays

int main()
{
float grades[5]= {0.0};
float* grdPtr =NULL;

grdPtr = grades; //points to the first element of the array

for(int i=0; i< 5; i++)


{
cout << "Input grade: ";
cin >> grades[i];
}
// print the contents of array using pointer
cout <<"\n\nThe following grades were entered: \n";
float sum,average;
for (int i=0;i<5;i++)
{
cout << endl << *grdPtr;
sum =sum + *grdPtr;
grdPtr++;
}
average = sum / 5;
cout << "\n\nAverage grade is " << average;

return 0;
}

150
Pointers

You can also use pointers to input values to your array

#include<iostream>
using namespace std;

//pointers and arrays

int main()
{
float grades[5]= {0.0};
float* grdPtr =NULL;

grdPtr = grades; //points to the first element of the array

// input array values using pointer


for(int i=0; i< 5; i++)
{
cout << "Input grade: ";
cin >> *(grdPtr+i); //same with cin >> grades[i];
}

// print the contents of array


cout <<"\n\nThe following grades were entered: \n";
float sum,average;
for (int i=0;i<5;i++)
{
cout << endl << grades[i];
sum =sum + grades[i];
}
average = sum / 5;
cout << "\n\nAverage grade is " << average;
return 0;
}

151
Pointers

Same output with program below:

#include<iostream>
using namespace std;

//pointers and arrays

int main()
{
float grades[5]= {0.0};
float* grdPtr =NULL;

grdPtr = grades; //points to the first element of the array

// input array values using pointer


for(int i=0; i< 5; i++)
{
cout << "Input grade: ";
cin >> *(grdPtr+i); // cin >> grades[i];
}

// print the contents of array


cout <<"\n\nThe following grades were entered: \n";
float sum,average;
for (int i=0;i<5;i++)
{
cout << endl << *(grdPtr+i);
sum =sum +*(grdPtr+i);
}
average = sum / 5;
cout << "\n\nAverage grade is " << average;

return 0;
}

cout << endl << *grdPtr; cout << endl << *(grdPtr+i);
sum =sum + *grdPtr; sum =sum +*(grdPtr+i);
grdPtr++;
same with

152
Pointers

Activities

1. Assume the definitions and initializations:

char c = 'T', d = 'S';


char *p1 = &c;
char *p2 = &d;
char *p3;

Assume further that the address of c is 8940, the address of d is 9882, and the address of e
is 3334. What will be printed when the following statements are executed sequentially?

p3 = &d;
cout << "*p3 = " << *p3 << endl;

p3 = p1;
cout << "*p3 = " << *p3 << ", p3 = " << p3 << endl;

*p1 = *p2;
cout << "*p1 = " << *p1 << ", p1 = " << p1 << endl;

2. Give the value of the left-hand side variable in each assignment statement. Assume the
lines are executed sequentially. Assume the address of the blocks array is 3343 .

int main()
{
char ARRAY[3] = {'E','V','A'};
char *ptr = &ARRAY[0];
char temp;

temp = ARRAY[0];
temp = *(ARRAY + 2);
temp = *(ptr + 1);
temp = *ptr;

ptr = ARRAY + 1;
temp = *ptr;
temp = *(ptr + 1);

ptr = ARRAY;
temp = *++ptr;
temp = ++*ptr;
temp = *ptr++;
temp = *ptr;

return 0;
}

153
Pointers

Programming

Modify the program below. Use pointers to sort and display the array grades in descending.

#include<iostream>
using namespace std;

//pointers and arrays

int main()
{
float grades[5]= {0.0};
float* grdPtr =NULL;

grdPtr = grades; //points to the first element of the array

// input array values using pointer


for(int i=0; i< 5; i++)
{
cout << "Input grade: ";
cin >> *(grdPtr+i); // cin >> grades[i];
}

// print the contents of array


cout <<"\n\nThe following grades were entered: \n";
float sum,average;
for (int i=0;i<5;i++)
{
cout << endl << *(grdPtr+i);
sum =sum +*(grdPtr+i);
}
average = sum / 5;
cout << "\n\nAverage grade is " << average;

return 0;
}

Online References

https://simplesnippets.tech/cpp-pointers-concept-with-example/

https://www.tutorialspoint.com/cplusplus/cpp_pointers.htm

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

154
References

Other References:

1. Farrel , Joyce, Programming Logic and Design, 2015.


2. Forouzan, Behrouz A. &Gilberg, Richard F. Foundations of C Programming, 2011.
3. Hanley, Jeri. Problem Solving & Program Design in C, 2016.
4. Tselikis, George S. C from Theory to Practice, 2014.
5. Deitel, Paul J. C How to Program, 2016.
6. Zak, Dianne. An Introduction to Programming with C++, 2016.
7. Mallik, D. S. C++ Programming Program Design Including Data Structures.

8. Deitel, Paul J. C How to Program, 2016.


9. Harper, Robert. Practical Foundations for Programming Languages, 2016.
10. Let us C by YashavantKanetkar

162
References

163

You might also like