Prog 1 Module
Prog 1 Module
Prog 1 Module
BY:
June 2020
Table of Contents
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 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
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
1
Programming Concepts
Course Materials
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).
- 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.
- 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. 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.
https://www.programiz.com/article/flowchart-programming
4
Programming Concepts
Find the largest among three different numbers entered by the user.
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.
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
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
Introduction
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++ 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
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
Some of today's most visible used systems have their critical parts written in C++.
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
Consider the famous “Hello World!” program of C language, and let’s examine every line
of it.
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.
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!”;
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
https://ecomputernotes.com/cpp/introduction-to-oop/structure-of-a-cpp
11
C Programming Language and Its Structure
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";
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:
int main()
{
for ( ; ; )
{
statement;
if ( condition)
{
statement;
}
else
{
statement;
}
statement;
}
}
Compared to:
int main() {
for ( ; ; ){
statement;
if ( condition) {
statement;
}
else {
statement;
}
statement;
}
}
13
C Programming Language and Its Structure
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:
Hello World!
Here in Laguna.
Spaces within the double quotation marks are counted and displayed.
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
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.
15
C Programming Language and Its Structure
Activities
#include<iosteam>
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:
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
Introduction
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
18
Data Types and Identifiers
Course Materials
The data type specifies the size and type of information the variable can store:
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
https://www.geeksforgeeks.org/c-data-types/
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:
Float 4
Double 8
long double 12
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
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.
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
https://www.tutorialspoint.com/cplusplus/cpp_basic_syntax.htm
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:
P o l y t e … \0
n
0 1 2 3 4 5 41 95 96 97 98 99
With the new version of C language, you can now use the string data type.
They are enclosed with double quotation marks ( “ “).
string schoolName = “ “;
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:
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
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
Course Materials
data_type variable_name;
data_type variable_name = value;
25
Variables and Constants
Variables must be declared before use, but normally, they are declared at the
beginning of the program.
Examples:
You can also declare multiple variables of the same type at the same time.
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;
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;
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;
return 0;
}
float grade1=0.0;
float grade2=0.0;
float grade3=0.0;
28
Variables and Constants
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 main()
{
int birthYear = 0; // this is a local varibale
:
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.
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
29
Variables and Constants
#include<iostream>
using namespace std;
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.
#include<iostream>
using namespace std;
int main()
{
const int currentYear = 2020; // this is a local constant
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.
or
currentYear = 2021;
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++.
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
Course Materials
Now that we know what are variables and constants, we can begin doing some operations
with them with the use of operators.
Assignment operators
Arithmetic operators
Comparison operators
Logical operators
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
32
Operators
taxiFareRate
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);
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
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:
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;
a =5; a = 5;
b = a; a = a + 1;
a = a + 1; b = a;
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
int x = 5;
int y = 3;
cout << (x > y); // returns 1 (true) because 5 is greater than 3
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.
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:
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
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:
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
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.
36
Operators
From greatest to smallest priority, C++ operators are evaluated in the following order:
37
Operators
Activities:
1. a = 6;
b = 10;
c = ++a * b--;
3. x = 3;
y = 7;
z = 8;
z += (x*y); x = ________ y = _______ z= _______
4. pupcet = 80;
hsAve = 78;
public = true;
5. 100 % 32 * 5 + 4 = _______
________________________________________________
________________________________________________
________________________________________________
_________________________________________________
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
Course Materials
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:
40
Comments
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. */
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
or
41
Comments
Activities:
Change the format of the following comments to make them easier to read.
/* *********************** __________________________
Program Name: Salary.cpp ______________________________
Programmer : Mr. XY Zhi ______________________________
Company: ABC Inc. ______________________________
************************* */
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 <<
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
Course Materials:
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.
or
43
cout <<
The extraction operator (<<) can be used more than once with a combination of
variables, strings and manipulators (like endl or \n).
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.
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;
}
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.
To make your output more readable, insert at least one space before displaying the
value of your variable.
45
cout <<
Example 3
#include <iostream>
using namespace std;
int main ()
{
int year = 2020;
cout << "Hello BSIT Batch " << year;
return 0;
}
Example 4
#include <iostream>
using namespace std;
int main ()
{
int currentYear = 2020;
int birthYear = 1989;
return 0;
}
46
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:
and
Hello
World!
if you want to put a blank space in between lines your statement must be like this
or
47
cout <<
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
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
The following escape sequences can be used along with the cout command
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;
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 <<
Infected = 25432
Recovered = 4235
Died = 1453
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>>
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
Course Materials:
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.
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>
int main()
{
int curYear =2020, birthYear =0, age = 0;
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>
int main()
{
int curYear =2020, birthYear =0, age = 0;
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>>
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>>
// 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;
}
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:
#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>>
// 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;
}
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.
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
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.
Learning Objectives
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
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:
int age =0 ;
:
cin >> age;
if (age >= 60){
cout << “SENIOR CITIZEN”;
}
64
If and switch
int age =0 ;
float price = 0.0;
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:
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’
Also note that conditions are written inside the parentheses () and there is no semicolon
after the close parenthesis.
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
}
67
If and switch
Examples:
cin >>x;
if (x >0)
cout << “x is positive”;
else if (x < 0)
cout << “x is negative”;
else
cout << “x is zero”;
cin>> grade;
68
If and switch
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
69
If and switch
70
If and switch
Why?
Remedy
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
Examples:
int number=0;
switch (number % 2) {
case 0: cout << "\n EVEN number";
break;
case 1: cout << "\n ODD number";
}
72
If and switch
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;
73
If and switch
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;
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 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;
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.
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..
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
5 – 10 Php 1800.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.
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:
77
If and switch
Discount: 178,194.50
Balance: 3,385,695.50
--------------------------------------------
--------------------------------------------
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
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
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:
statement 1 – initializes the control variable (int or char type), executed only once
at the start of loop.
statement 3 – executed after executing the block of codes. This should increment or
increment the value of the variable in statement 1.
Examples:
abcdefghIjklmnopqrstuvwxyz
81
for loop
10.2 Nested for loop – is a for loop statement within another for loop statement
Syntax:
82
for loop
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;
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!”;
}
break; Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.
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.
for (; ;){
Activities
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
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:
@@@@@@ @@@@@@
@@@@@ @@@@@
@@@@ @@@@
@@@ @@@
@@ @@
@ @
2. Ask the user to enter a name (one word only) and then print the name in the form of
letter ‘V’
Example:
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! .
For example,
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
Introduction
Learning Objectives:
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.
90
while and do…while loop
91
while and do…while loop
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;
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:
// 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.
// If the choice or values to be entered are not in sequence. Example, gender ‘M’ for
male and ‘F’ for female
93
while and do…while loop
while (condition) {
while (condition) {
// statement(s) of inside loop
}
// statement of outer 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(){
94
while and do…while loop
do {
i++;
total = 0.0;
cout << "\n Enter quarterly grades of student #" <<i <<endl;
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 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;
}
sum = 0;
sum = sum + I;
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:
96
while and do…while loop
Programming Exercises
Write a program that will incorporate while or do…while statements to do the following:
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.
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/
99
Array
Three-Dimensional Array
https://www.geeksforgeeks.org/multidimensional-arrays-c-cpp/
Learning Objectives
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.
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.
Syntax:
data_type arrayName[size];
Examples:
int age[10];
0 1 2 3 4 5 6 7 8 9
6 72 47 13 23
0 1 2 3 4
101
Array
0 0 0 0 0 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
6 72 47 13 23 0 0 0 0 0
0 1 2 3 4 5 6 7 8 9
0 1 2
0 1 2 3 4
0 1 2 3 4 5 6 … 48 49
Direct:
studName[3] = “Beniah”;
102
Array
You can ask the user to enter the exact or estimated size of the array.
103
Array
104
Array
12.7 Counting – based on the criteria count how many in the array met the criteria.
12.7 Searching an array – finding data that match the given requirement.
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.
int j;
int holdAge=0;
float holdGrade=0.0;
string holdName = " ";
bool swapped;
105
Array
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 (swapped == false)
break;
}
106
Array
Activities
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
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.
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.
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
Course Materials
1. Pre-defined or Standard Library Function. The library functions are declared in header
files and defined in library files.
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 main() {
int a = 0, b = 0, m=0;
Example 2:
#include <iostream>
using namespace std;
int main() {
int a = 0, b = 0, m=0;
111
Functions
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
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:
112
Functions
Return-type
Function name
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);
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
Syntax:
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 main() {
int a = 0, b = 0, m=0;
Note: The type of the arguments passed while calling the function must match with the
corresponding parameters defined in the function declaration.
114
Functions
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.
Examples:
return x;
return 10;
return (a+b)/2;
#include <iostream>
using namespace std;
int inputData(void);
int ifEven(int);
int main()
{
int num=0,even=0;
115
Functions
int inputData(void)
{
int n=0; //local variable
int ifEven(int n)
{
if (n%2 == 0)
return 1;
else
return 0;
}
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.
#include <iostream>
using namespace std;
int main()
{
//add two values
addition(); //function call
cout<< "\n\nDONE";
}
void addition(void)
{
int n1,n2; //local variables
116
Functions
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";
}
main()
45 64
n1 n2
addition()
45 64 109
N1 N2 sum
Computer Memory
117
Functions
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;
int main()
{
int n1,n2,sum;
addition(n1,n2);
sum = n1 + n2;
cout << "\n\n Sum = " << sum;
cout<< "\n\n DONE";
}
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;
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";
}
Example:
#include<iostream>
using namespace std;
119
Functions
int main()
{
Entries();
return 0;
}
120
Functions
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>
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);
return 0;
}
121
Functions
122
Functions
https://www.programiz.com/cpp-
The following text and samples were taken from https://www.programiz.com/cpp
programming/recursion
void recurse()
{
... .. ...
recurse();
... .. ...
}
int main()
{
... .. ...
recurse();
... .. ...
}
The figure below shows how recursion works by calling itself over and over again.
123
Functions
// Factorial of n = 1*2*3*...*n
#include <iostream>
using namespace std;
int factorial(int);
int main() {
int n, result;
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
124
Functions
125
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.
#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
1.
# include <iostream>
using namespace std;
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;
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;
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)
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:
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
Introduction
In C++, string data type is used for declaring string variable that can contain a
collection of characters surrounded by double quotes.
Learning Objectives
Course Materials
14.1 C-Style String – are actually an array of type char terminated by a null character ‘ \0’.
Examples:
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:
In his module, we will discuss the string class because it has more functions that are
much easier to use.
// declaring only
string str0;
133
String Manipulation
Assignment Operator ( = )
name.clear();
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
cout << city << “ found in “ << address <<” at " <<
address.find(city) << " pos" << endl;
else
cout << city <<” not found in " << address << endl;
address.erase(0, 4);
cout << address << endl;
address.replace(0, 3, "123”);
cout << address << endl;
transform(address.begin(),address.end(),address.begin(),::toupper);
cout << address;
135
String Manipulation
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.”;
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;
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;
#include<iostream>
#include<algorithm>
int main()
{
// various constructor of string class
string str0="\0";
// 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
//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");
// 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");
//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:
2. determines if the code variable contains either ‘X’ or ’x’. use tolower function in the if
clause
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”
7. determine if the mobile phone number entered in celNo was complete (11 digits)
142
String Manipulation
10. get the 3rd and 4th character in variable employNumber and assign it to deptCode
Programming
- 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
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.
143
String Manipulation
Address: B29 L36 New York St. Green State Subd. Brgy. Ibaba, Carmona, Cavite
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
Introduction
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:
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.
Syntax:
data-type *pointerVariableName;
data-type is the type of data that it will point (int, float, double, char ….)
Examples:
For example:
pointerVariableName = &variableName
*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
147
Pointers
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
4 Array of Pointers
5 Pointer to Pointer
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
int main()
{
float grades[5]= {0.0};
float* grdPtr =NULL;
Note: The highlighted lines can be replaced with: cout << endl << *(grdPtr+i);
149
Pointers
#include<iostream>
using namespace std;
int main()
{
float grades[5]= {0.0};
float* grdPtr =NULL;
return 0;
}
150
Pointers
#include<iostream>
using namespace std;
int main()
{
float grades[5]= {0.0};
float* grdPtr =NULL;
151
Pointers
#include<iostream>
using namespace std;
int main()
{
float grades[5]= {0.0};
float* grdPtr =NULL;
return 0;
}
cout << endl << *grdPtr; cout << endl << *(grdPtr+i);
sum =sum + *grdPtr; sum =sum +*(grdPtr+i);
grdPtr++;
same with
152
Pointers
Activities
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;
int main()
{
float grades[5]= {0.0};
float* grdPtr =NULL;
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:
162
References
163