CPE 204 Lecture Notes
CPE 204 Lecture Notes
What is C++?
C++ is an important programming language for students and working professionals to become a
great Software Developer. The key advantages of learning C++ are:
C++ is very close to hardware, it works at a low level which gives a full control in terms
of memory management, better performance and finally a robust software development.
C++ programming gives you a clear understanding about Object Oriented Programming.
You will understand low level implementation of polymorphism when you will implement
virtual tables and virtual table pointers, or dynamic type identification.
C++ is one of the every green programming languages and loved by millions of software
developers. If you are a great C++ programmer then you will never sit without work and
more importantly you will get highly paid for your work.
C++ is the most widely used programming languages in application and system
programming. So you can choose your area of interest of software development.
C++ really teaches you the difference between compiler, linker and loader, different data
types, storage classes, variable types their scopes etc.
Just to give you a little excitement about C++ programming, Lets see a small conventional C++
Hello World program as shown below.
There are many C++ compilers available which you can use to compile and run above program:
Features of C++
As stated earlier, C++ is one of the most widely used programming languages. It has it's presence
in almost every area of software development.
This list goes on, there are various areas where software developers are happily using C++ to
provide great softwares. C++ is a statically typed, compiled, general-purpose, case-sensitive,
free-form programming language that supports procedural, object-oriented, and generic
programming.
C++ as Object-Oriented Programming
C++ fully supports object-oriented programming, including the four pillars of object-oriented
development −
Get started learning C++ with the first program by printing "Hello World" on the console −
Advantages of C++
C++ programming language has many advantages over other languages. Some of these
advantages are listed as follows −
Rich Standard Library: C++ language provides the users with a rich and useful Standard
Template Library (STL). This library has a lot of in-built methods and data structure
templates to make coding in this language efficient and quick.
OOPS Concepts: C++ language provides users with Object-Oriented Programming
concepts like class, object, abstraction, polymorphism and much more. Hence, it acts as a
modified and better version of C programming language.
Faster Performance: C++ language is faster in comparison to other languages
like Python, Go, C#, and many more. This makes it very useful in embedded systems and
gaming processors.
Efficient Compiler: C++ is a compiled language. C++ compiler is very versatile, and it
can accept both procedural programs as well as object oriented programs.
Hardware Independent: C++ language is independent of any hardware or system design.
C++ programs work on any system that has a C++/GCC compiler installed and enabled in
it.
Large Support Base: C++ is one of the most widely used programming languages across
the globe. It has a vast community of developers and programmers. This can be explored
on platforms like Github, Reddit, Discord, DEV, Stack Overflow, and many more.
Disadvantages of C++
C++ programming language also has some disadvantages, which are listed below:
Error Detection: C++ provides the facility of low-level design and is very close to the
hardware of the system. Hence, this may lead the user to carry out small errors that are
difficult to observe and detect.
Large Syntax: C++ has a very lengthy code base, and many programmers find it difficult
to write such a lengthy syntax. This has drawn backlash from the user-base of languages
like Python, Go, etc., which are easier to code and simpler to execute.
Learning Curve: As compared to Python and Go, C++ has a very steep learning curve.
Users feel that the initial building phase is very tough to learn, and there are many concepts
that beginners find difficult to understand.
Here are some interesting and lesser-known facts about the C++ programming language −
C++ language was invented at the AT&T Bell Labs, the same place where C language was
invented.
C++ language is heavily used in NASA, where it finds applications in flight software and
command design.
C++ is the successor of the C language. The name C++ has been taken from C only, and
the increment operator ('++') signifies that this language is the next version of C.
C++ is widely used in areas like game development, server-side networking, TCP/IP
connections, low-level design, and many more.
C++ programs begin by executing the main() function, and other functions are redirected
using the main() function only.
C++ has inherited almost all features of C, and it has incorporated OOPS concepts from
Simula68 programming language.
C++ does not support pure object-oriented programming. Programs can be executed
without the use of classes and objects, just like in procedural languages.
There are many languages that are conceptualized using C++, and some of those are
C#, Java, JavaScript, and many more.
When we consider a C++ program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what a class, object, methods,
and instant variables mean.
Object − Objects have states and behaviors. Example: A dog has states - color, name, breed
as well as behaviors - wagging, barking, eating. An object is an instance of a class.
Class − A class can be defined as a template/blueprint that describes the behaviors/states
that object of its type support.
Methods − A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are executed.
Instance Variables − Each object has its unique set of instance variables. An object's state
is created by the values assigned to these instance variables.
Header file section: This is the section where we include all required header files whose
functions we are going to use in the program.
Namespace section: This is the section where we use the namespace.
The main() section: In this section, we write our main code. The main() function is an
entry point of any C++ programming code from where the program's execution starts.
Example
Let us look at a simple code that would print the words Hello World.
The C++ language defines several headers, which contain information that is either
necessary or useful to your program. For this program, the header <iostream> is needed.
The line using namespace std; tells the compiler to use the std namespace. Namespaces
are a relatively recent addition to C++.
The next line '// main() is where program execution begins.' is a single-line comment
available in C++. Single-line comments begin with // and stop at the end of the line.
The line int main() is the main function where program execution begins.
The next line cout << "Hello World"; causes the message "Hello World" to be displayed
on the screen.
The next line return 0; terminates main() function and causes it to return the value 0 to the
calling process.
In C++, the semicolon is a statement terminator. That is, each individual statement must be
ended with a semicolon. It indicates the end of one logical entity.
For example, following are three different statements −
A block is a set of logically connected statements that are surrounded by opening and closing
braces. For example –
C++ does not recognize the end of the line as a terminator. For this reason, it does not matter
where you put a statement in a line. For example –
is the same as
C++ Identifiers
A C++ identifier is a name used to identify a variable, function, class, module, or any other user-
defined item. An identifier 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, CPE and cpe are two different identifiers in C++.
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.
C++ Comments
Program comments are explanatory statements that you can include in the C++ code. These
comments help anyone reading the source code. All programming languages allow for some
form of comments.
C++ supports two types of comments: single-line comments and multi-line comments. All
characters available inside any comment are ignored by the C++ compiler.
A single-line comment starts with //, extending to the end of the line. These comments can last
only till the end of the line, and the next line leads to a new comment.
Example
Multi-line comments start with /* and end with */. Any text in between these symbols is treated
as a comment only.
Syntax
Example
Example
The following example explains the usage of multi-line comments within statements −
Example
The following example explains the usage of single-line comments within statements −
Purpose of Comments
Comments are used for various purposes in C++. Some of the main areas of application of
comments are given as follows:
To represent a short and concise step in the program for users to understand better.
To explain a step in a detailed way that is not expressed explicitly in the code.
To leave different hints for users to grab in the code itself.
To leave comments for fun or recreation.
To temporarily disable part of the code for debugging purposes.
To add metadata to the code for future purposes.
To create documentation for the code, for example, in Github pages.
C++ offers the programmer a rich assortment of built-in as well as user defined data types.
Following table lists down seven basic C++ data types −
The following table shows the variable type, how much memory it takes to store the value in
memory, and what is maximum and minimum value which can be stored in such type of
variables.
The size of variables might be different from those shown in the above table, depending on the
compiler and the computer you are using.
Example
Following is the example, which will produce correct size of various data types on your
computer.
This example uses endl, which inserts a new-line character after every line and << operator is
being used to pass multiple values out to the screen. We are also using sizeof() operator to get
size of various data types.
Data types which are obtained from pre-defined data types in C++ are known as Derived Data
Types. These can be classified into four categories, namely −
1. Function
A function is the simplest form of user-defined data type. It includes a return type, a function
name and input parameters.
Syntax
Example
2. Array
An array is a series of elements of same data type. Elements of an array are stored in contiguous
memory locations in the storage.
Syntax
Example
3. Pointer
A pointer is a reference to an element defined previously. The value of the pointer returns the
address location of the element which is associated with it.
Syntax
Data types which are defined by the user intuitively without using any pre-defined data types are
known as User-Defined Data Types. These data types can be further categorized into five types,
namely:
1. Class
A class is a defined in Object Oriented Programming as a custom data type which is used to
construct an object. It is the framework of an object, and it can include constructors, methods and
OOP concepts like Polymorphism, Inheritance, etc.
Syntax
Example
The int data type is short for integer, which takes numeric values from -231 to (231-1). It takes 4
Bytes (i.e., 32 bits) in the memory.
Syntax
int variable_name;
Syntax
float elem_name;
The double data type is used to store floating-point elements with double precision as compared
to float. This data type takes 8 Bytes (i.e., 64 bits) of memory.
Syntax
double elem_name;
C++ Variable
A variable provides us with named storage that our programs can manipulate. Each variable in
C++ has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore character. It must
begin with either a letter or an underscore. Upper and lowercase letters are distinct because C++
is case-sensitive.
A scope is a region of the program and broadly speaking there are three places, where variables
can be declared. C++ variables scopes are categorized into two parts −
Local Variables
Global Variables
Local Variables
Variables that are declared inside a function or block are local variables. They can be used only
by statements that are inside that function or block of code. Local variables are not known to
functions outside their own.
Example
Global Variables
Global variables are defined outside of all the functions, usually on top of the program. The
global variables will hold their value throughout the life-time of your program. A global variable
can be accessed by any function. That is, a global variable is available for use throughout your
entire program after its declaration.
Example
Example
When the above code is compiled and executed, it produces the following result − 10
You can access a global variable when there is a local variable with the same name by using
the SRO (Scope Resolution Operator) :: before the name of that variable.
Example
In the following example, we have global and local variables with the same name, and accessing
and printing the value of the global variable −
When the above code is compiled and executed, it produces the following result −
The C++ standard libraries provide an extensive set of input/output capabilities. This chapter will
discuss very basic and most common I/O operations required for C++ programming.
C++ I/O occurs in streams, which are sequences of bytes. If bytes flow from a device like a
keyboard, a disk drive, or a network connection etc. to main memory, this is called input
operation and if bytes flow from main memory to a device like a display screen, a printer, a disk
drive, or a network connection, etc., this is called output operation.
Operators in C++
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C++ is rich in built-in operators and provide the following types of operators −
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
This chapter will examine the arithmetic, relational, logical, bitwise, assignment and other
operators one by one.
1. Arithmetic Operators: Arithmetic operators in C++ are the basic operators, which are
used for basic mathematical or arithmetical operations on operands. These operators are
essential for performing calculations and manipulating data within a program.
Example
#include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
cout << "Line 1 - Value of c is :" << c << endl ;
c = a - b;
cout << "Line 2 - Value of c is :" << c << endl;
c = a * b;
cout << "Line 3 - Value of c is :" << c << endl ;
c = a / b;
cout << "Line 4 - Value of c is :" << c << endl ;
c = a % b;
cout << "Line 5 - Value of c is :" << c << endl ;
c = a++;
cout << "Line 6 - Value of c is :" << c << endl ;
c = a--;
cout << "Line 7 - Value of c is :" << c << endl ;
return 0;
Output
Line 1 - Value of c is :31
Line 2 - Value of c is :11
Line 3 - Value of c is :210
Line 4 - Value of c is :2
Line 5 - Value of c is :1
Line 6 - Value of c is :21
Line 7 - Value of c is :22
2. Relational Operators
Relational operators are used to compare two values or expressions. These operators return a
boolean value − true if the comparison is correct, and else false. They are essential for making
decisions and controlling the flow of a program based on conditions. There are following
relational operators supported by C++ language
#include <iostream>
using namespace std;
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
cout << "Line 1 - a is equal to b" << endl ;
} else {
cout << "Line 1 - a is not equal to b" << endl ;
}
if( a < b ) {
cout << "Line 2 - a is less than b" << endl ;
} else {
cout << "Line 2 - a is not less than b" << endl ;
}
if( a > b ) {
cout << "Line 3 - a is greater than b" << endl ;
} else {
cout << "Line 3 - a is not greater than b" << endl ;
}
if( b >= a ) {
cout << "Line 5 - b is either greater than \ or equal to b" << endl ;
}
return 0;
Output
Line 1 - a is not equal to b
Line 2 - a is not less than b
Line 3 - a is greater than b
Line 4 - a is either less than or equal to b
Line 5 - b is either greater than or equal to b
3. Logical Operators
Logical operators are used to perform logical operations on boolean values (true or false). These
operators are essential for controlling the flow of a program based on conditions. There are three
primary logical operators in C++ as mentioned below −
#include <iostream>
using namespace std;
main() {
int a = 5;
int b = 20;
int c ;
if(a && b) {
cout << "Line 1 - Condition is true"<< endl ;
}
if(a || b) {
cout << "Line 2 - Condition is true"<< endl ;
}
if(a && b) {
cout << "Line 3 - Condition is true"<< endl ;
} else {
cout << "Line 4 - Condition is not true"<< endl ;
}
return 0;
}
Output
Line 1 - Condition is true
Line 2 - Condition is true
Line 4 - Condition is not true
Line 5 - Condition is true
4. Bitwise Operators
Bitwise operators are used to perform operations at the bit level on integer data types. These
operations work on direct manipulation of bits, such as low-level programming, graphics, and
cryptography. Bitwise operator works on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows −
Assume if A = 60; and B = 13; now in binary format they will be as follows −
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The Bitwise operators supported by C++ language are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then −
Example
#include <iostream>
using namespace std;
main() {
unsigned int a = 60; // 60 = 0011 1100
unsigned int b = 13; // 13 = 0000 1101
int c = 0;
c = a | b; // 61 = 0011 1101
cout << "Line 2 - Value of c is: " << c << endl ;
c = a ^ b; // 49 = 0011 0001
cout << "Line 3 - Value of c is: " << c << endl ;
return 0;
Output
Line 1 - Value of c is : 12
Line 2 - Value of c is: 61
Line 3 - Value of c is: 49
Line 4 - Value of c is: -61
Line 5 - Value of c is: 240
Line 6 - Value of c is: 15
5. Assignment Operators
Assignment operators are used to assign values to variables. These operators allow you to set or
update the value stored in a variable.
Example
#include <iostream>
using namespace std;
main() {
int a = 21;
int c ;
c = a;
cout << "Line 1 - = Operator, Value of c = : " <<c<< endl ;
c += a;
cout << "Line 2 - += Operator, Value of c = : " <<c<< endl ;
c -= a;
cout << "Line 3 - -= Operator, Value of c = : " <<c<< endl ;
c *= a;
cout << "Line 4 - *= Operator, Value of c = : " <<c<< endl ;
c /= a;
cout << "Line 5 - /= Operator, Value of c = : " <<c<< endl ;
c = 200;
c %= a;
cout << "Line 6 - %= Operator, Value of c = : " <<c<< endl ;
c <<= 2;
cout << "Line 7 - <<= Operator, Value of c = : " <<c<< endl ;
c >>= 2;
cout << "Line 8 - >>= Operator, Value of c = : " <<c<< endl ;
c &= 2;
cout << "Line 9 - &= Operator, Value of c = : " <<c<< endl ;
c ^= 2;
cout << "Line 10 - ^= Operator, Value of c = : " <<c<< endl ;
c |= 2;
cout << "Line 11 - |= Operator, Value of c = : " <<c<< endl ;
return 0;
Output
Line 1 - = Operator, Value of c = : 21
Line 2 - += Operator, Value of c = : 42
Line 3 - -= Operator, Value of c = : 21
Line 4 - *= Operator, Value of c = : 441
Line 5 - /= Operator, Value of c = : 21
Line 6 - %= Operator, Value of c = : 11
Line 7 - <<= Operator, Value of c = : 44
Line 8 - >>= Operator, Value of c = : 11
Line 9 - &= Operator, Value of c = : 2
Line 10 - ^= Operator, Value of c = : 0
Line 11 - |= Operator, Value of c = : 2
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Decision making structures require that the programmer specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages –
C++ programming language provides following types of decision making statements
if statement
1
An ‘if’ statement consists of a boolean expression followed by one or more statements.
if...else statement
2 An ‘if’ statement can be followed by an optional ‘else’ statement, which executes when the
boolean expression is false.
switch statement
3
A ‘switch’ statement allows a variable to be tested for equality against a list of values.
nested if statements
4
You can use one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).
1. The if Statement
Use the if statement to specify a block of C++ code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Example
int x = 20;
int y = 18;
if (x > y) {
cout << "x is greater than y";
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
}
Example
int time = 20;
if (time < 18) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
Example
int time = 22;
if (time < 10) {
cout << "Good morning.";
} else if (time < 20) {
cout << "Good day.";
} else {
cout << "Good evening.";
}
// Outputs "Good evening."
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
Explanations
The example below uses the weekday number to calculate the weekday name:
Example
int day;
cout<<”Enter day number: ”;
cin>>day;
switch (day) {
case 1:
cout << "Monday";
break;
case 2:
cout << "Tuesday";
break;
case 3:
cout << "Wednesday";
break;
case 4:
cout << "Thursday";
break;
case 5:
cout << "Friday";
break;
case 6:
cout << "Saturday";
break;
case 7:
cout << "Sunday";
break;
default:
cout << "Invalid choice";
}
// Outputs the day
When C++ reaches a break keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
Syntax
while (condition) {
// code block to be executed
}
In the example below, the code in the loop will run, over and over again, as long as a variable (i)
is less than 5:
Example
int i = 0;
while (i < 5) {
cout << i << "\n";
i++;
}
The do/while loop is a variant of the while loop. This loop will execute the code block once,
before checking if the condition is true, then it will repeat the loop as long as the condition is
true.
Syntax
do {
// code block to be executed
}
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if
the condition is false, because the code block is executed before the condition is tested:
Example
int i = 0;
do {
cout << i << "\n";
i++;
}
while (i < 5);
In this example, a program that only print even numbers between 0 and 10 (inclusive):
Example
int i = 0;
Syntax
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (int i = 0; i < 5; i++)
{
cout << i << "\n";
}
Example explained
Statement 3 increases a value (i++) each time the code block in the loop has been executed.
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
// Outer loop
for (int i = 1; i <= 2; ++i) {
cout << "Outer: " << i << "\n"; // Executes 2 times
// Inner loop
for (int j = 1; j <= 3; ++j) {
cout << " Inner: " << j << "\n"; // Executes 6 times (2 * 3)
}
}
C++ Arrays
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value.
To declare an array, define the variable type, specify the name of the array followed by square
brackets and specify the number of elements it should store:
string cars[4];
We have now declared a variable that holds an array of four strings. To insert values to it, we can
use an array literal - place the values in a comma-separated list, inside curly braces:
You can loop through the array elements with the for loop.
Example
// Create an array of strings
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
This example outputs the index of each element together with its value:
Example
string cars[5] = {"Volvo", "BMW", "Ford", "Mazda", "Tesla"};
for (int i = 0; i < 5; i++) {
cout << i << " = " << cars[i] << "\n";
}
C++ Functions
Functions are used to perform certain actions, and they are important for reusing code: Define
the code once, and use it many times.
Create a Function
C++ provides some pre-defined functions, such as main(), which is used to execute code. But
you can also create your own functions to perform certain actions.
To create (often referred to as declare) a function, specify the name of the function, followed by
parentheses ():
Syntax
void myFunction() {
// code to be executed
}
Example Explained
Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be
executed later, when they are called.
To call a function, write the function's name followed by two parentheses () and a semicolon ;
In the following example, myFunction() is used to print a text (the action), when it is called:
Example
Inside main, call myFunction():
// Create a function
void myFunction() {
cout << "I just got executed!";
}
int main() {
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
A function can be called multiple times:
Example
void myFunction() {
cout << "I just got executed!\n";
}
int main() {
myFunction();
myFunction();
myFunction();
return 0;
}
void myFunction() {
cout << "I just got executed!";
}
// Error
However, it is possible to separate the declaration and the definition of the function - for code
optimization.
You will often see C++ programs that have function declaration above main(), and function
definition below main(). This will make the code better organized and easier to read:
Example
// Function declaration
void myFunction();
// Function definition
void myFunction() {
cout << "I just got executed!";
}
C++ Function Parameters
Parameters and Arguments
Information can be passed to functions as a parameter. Parameters act as variables inside the
function.
Parameters are specified after the function name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma:
Syntax
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
The following example has a function that takes a string called fname as parameter. When the
function is called, we pass along a first name, which is used inside the function to print the full
name:
Example
void myFunction(string fname) {
cout << fname << " Refsnes\n";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes