COSC301 Lecture Notes
COSC301 Lecture Notes
(COSC301)
LECTURE NOTE 1
Credit unit: 3
Assessment Breakdown
Recommended textbooks: see the student handbook for the syllabus and list of
recommended books.
Course Objectives
Laboratory Instructions
1. Students are expected to attend all the lab sessions and ensure that they have
attempted all the lab exercises.
2. Students are expected to seek for help from the course lecturer whenever they
encountered any problem while attempting the lab exercises.
The objective of this course is to study the concept of object oriented programming
and how it is applied in C++ programming language, let us dive properly into defining
the concept of object oriented programming (OOP).
What is an object?
There are four basic principles or tenets of object oriented programming, they are:
inheritance, polymorphism, abstraction and encapsulation.
1. It provides a clear modular structure for programs which makes it good for
defining abstract datatypes in which implementation details are hidden
2. The objects created can be reused within an across applications, hence OOP
lowers the cost of software development.
3. It makes the modification of existing code less tedious as new objects can be
created with small differences to existing ones.
4. It makes software easier to maintain, because the design is modular, hence,
locating and fixing problems becomes less tedious.
5. It provides a good framework for code libraries where the supplied software
components can be easily adapted and modified by the programmer.
Since C was a successful computer programming language, why was there a need for
something else? The answer is complexity. Throughout the history of programming,
the increasing complexity of programs has driven the need for better ways to manage
that complexity. C++ is a response to that need.
C++ is one of the most important programming languages, because almost all the
programs/systems that we use today have some part of the code base that is written
in C/C++. Be it Windows, be it the photo editing software, be it your favourite game,
be it your web browser, C++ plays an integral role in almost all applications that we
use, some of the interesting areas where C++ is popularly used are:
1. Operating Systems
Be it Microsoft Windows or Mac OSX or Linux – all of them are programmed in C++.
C/C++ is the backbone of all the well-known operating systems owing to the fact that
it is a strongly typed and a fast programming language which makes it an ideal choice
for developing an operating system. Moreover, C++ is quite close to the assembly
language which further helps in writing low-level operating system modules.
2. Browsers
The rendering engines of various web browsers are programmed in C++ simply
because of the speed that it offers. The rendering engines require faster execution to
3. Libraries
Many high-level libraries use C++ as the core programming language. For instance,
several Machine Learning libraries use C++ in the backend because of its speed.
Tensorflow, one of the most widely used Machine Learning libraries uses C++ as the
backend programming language. Such libraries required high-performance
computations, because they involve multiplications of huge matrices for the purpose
of training Machine Learning models. As a result, performance becomes critical. C++
comes to the rescue in such libraries.
4. Graphics
All graphics applications require fast rendering and just like the case of web browsers,
here also C++ helps in reducing the latency. Software that employ computer vision,
digital image processing, high-end graphical processing mostly use C++ as the
backend programming language. Even the popular games that are heavy on graphics
use C++ as the primary programming language. The speed that C++ offers in such
situations helps the developers in expanding the target audience, because an
optimized application can run even on low-end devices that do not have high
computation power available.
5. Cloud/Distributed Systems
Large organizations that develop cloud storage systems and other distributed systems
also use C++ because it connects very well with the hardware and is compatible with
a lot of machines. Cloud storage systems use scalable file-systems that work close to
the hardware. C++ becomes a preferred choice in such situations because it is close
to the hardware and also the multithreading libraries in C++ provide high concurrency
and load tolerance which is very much needed in such scenarios.
6. Databases
7. Embedded Systems
Various embedded systems like medical machines, smartwatches, etc. use C++ as
the primary programming language because of the fact that C++ is closer to the
hardware level as compared to other high-level programming languages.
8. Compilers
The compilers of various programming languages use C and C++ as the backend
programming language. This is because of the fact that both C and C++ are relatively
lower level languages and are closer to the hardware and therefore are the ideal
choice for such compilation systems.
In summary, if we look at these areas where C++ is put into use, we can
observe that C++ is used in most advanced applications that play a vital role in
making the world a better place, thus, learning how to write C++ code is very important
and rewarding. C++ has so many advantages which include: Rich library support,
speed in terms of compilation and execution. It also has support for pointer.
#include <iostream>
Lines beginning with a hash sign (#) are directives for the preprocessor. They are not
regular code lines with expressions but indications for the compiler's preprocessor. In
this case the directive #include <iostream> tells the preprocessor to include the
iostream standard file. This specific file (iostream) includes the declarations of the
basic standard input-output library in C++, and it is included because its functionality
is going to be used later in the program.
All the elements of the standard C++ library are declared within what is called a
namespace, the namespace with the name std. So in order to access its functionality
we declare with this expression that we will be using these entities. This line is very
frequent in C++ programs that use the standard library.
int main ()
This line corresponds to the definition of the main function. The main function is the
point where all C++ programs start their execution, independently of its location within
the source code. It does not matter whether there are other functions with other names
defined before or after it – the instructions contained within this function's definition will
always be the first ones to be executed in any C++ program. For that same reason, it
is essential that all C++ programs have a main function.
The word main is followed in the code by a pair of parentheses (()), because it is a
function declaration: In C++, what differentiates a function declaration from other types
of expressions are these parentheses that follow its name. Optionally, these
parentheses may enclose a list of parameters within them. Right after these
parentheses we can find the body of the main function enclosed in braces ({}). What
is contained within these braces is what the function does when it is executed.
Notice that the statement ends with a semicolon character (;). This character is used
to mark the end of the statement and in fact it must be included at the end of all
expression statements in all C++ programs (one of the most common syntax errors is
indeed to forget to include some semicolon after a statement).
return 0;
The return statement causes the main function to finish, return may be followed by a
return code (in our example is followed by the return code 0). A return code of 0 for
the main function is generally interpreted as the program worked as expected without
any errors during its execution. This is the most usual way to end a C++ console
program.
The compilation of a C++ program involves a series of actions which operates on the
C++ source file (source code). The source code written by the programmer is saved
with a .cpp file extension (e.g. firstCode.cpp) and passed to the C++ compiler. The
compiler now perform the following steps.
A token is the smallest element of a C++ program that is meaningful to the compiler.
The C++ parser recognizes these kinds of tokens which may be identifiers, keywords,
literals, operators, punctuators, and other separators. A stream of these tokens
makes up a translation unit. Tokens are usually separated by white space. White
space can be one or more: blanks, horizontal / vertical tabs, new lines.
• Keywords
• Identifiers
• Constants
• Special Symbols
• Operators
There are certain rules which should be followed while naming C++ identifiers, all
identifiers
allowed.
3. Must not be a keyword.
Identifier Remark
_cosc301 Valid
123SaveCost Invalid because it starts with numeric value
Age.Year Invalid because of special character (.)
Special Symbols: The following special symbols are used in C++ and they have
some special meaning, thus, cannot be used for some other purpose. These special
symbols include:
• Parentheses ( ) - These special symbols are used to indicate function calls and
function parameters.
• Braces { } -These opening and ending curly braces marks the start and end of
a block of code containing more than one executable statement.
Constants: Constants are also like normal variables, however, the only difference is
that, their values cannot be modified by the program once they are defined. Constants
refer to fixed values, they are also called literals. The syntax for defining a constant
variable is:
const data_type variable_name;
Types of Constants:
1. Integer constants – Example: 0, 1, 1218, 12482
2. Real or Floating point constants – Example: 0.0, 1203.03, 30486.184
3. String constants -Example: “helloworld”
• Unary Operators: Those operators that require only single operand to act upon
are known as unary operators. For example increment and decrement
operators. Example i++
• Binary Operators: Those operators that require two operands to act upon are
called binary operators, for example a+b. Binary operators are classified into:
• Ternary Operators: These operators require three operands to act upon. For
Example Conditional operator (?:).
All variables use data-type during declaration to restrict the type of data to be stored.
Therefore, we can say that data types are used to tell the variables the type of data it
can store. Whenever a variable is defined in C++, the compiler allocates some memory
for that variable based on the data-type with which it is declared. Every data type
requires different amount of memory. The data type in C++ is mainly divided into two:
1. Primitive Data Types: These data types are built-in or predefined data types and
can be used directly by the user to declare variables. Some of the primitive data
types available in C++ are explained below:
• Integer: Keyword used for integer data types is int. Integers typically requires 4
bytes of memory space and ranges from -2147483648 to 2147483647.
• Boolean: Boolean data type is used for storing boolean or logical values. A
boolean variable can store either true or false. Keyword used for boolean data type
is bool.
• Floating Point: Floating Point data type is used for storing single precision floating
point values or decimal values. Keyword used for floating point data type is float.
Float variables typically requires 4 byte of memory space.
• Double Floating Point: Double Floating Point data type is used for storing double
precision floating point values or decimal values. Keyword used for double floating
point data type is double. Double variables typically requires 8 byte of memory
space.
• Void: Void means without any value. void datatype represents a valueless entity.
Void data type is used for those function which does not returns a value.
2. Abstract or User Defined Data Type: These data types are defined by user itself.
Like, defining a class in C++ or a structure (struct).
Data type modifiers are used with the built-in data types to modify the length of data
that a particular data type can hold. Data type modifiers available in C++ are:
• Signed
• Unsigned
• Short
• Long
Below table summarizes the modified size and range of built-in datatypes when
combined with the type modifiers:
C++ is a strongly-typed language, and requires every variable to be declared with its
type before its first use. This informs the compiler the size to reserve in memory for
the variable and how to interpret its value. The syntax to declare a new variable in C++
is straightforward: we simply write the type followed by the variable name (i.e., its
identifier). For example:
int number;
float decimalNumber;
These are two valid declarations of variables. The first one declares a variable of
type int with the identifier number. The second one declares a variable of
type float with the identifier decimalNumber. Once declared, the
variables number and decimalNumber can be used within the rest of their scope in the
program. If declaring more than one variable of the same type, they can all be declared
in a single statement by separating their identifiers with commas. For example:
int a, b, c;
int a;
int b;
int c;
When the variables are declared, they have an undetermined value until they are
assigned a value for the first time. A variable is said to be initialized when a specific
value is assigned to it when it was initially declared. This is called the initialization of
the variable. In C++, there are three ways to initialize variables. They are all equivalent
and are reminiscent of the evolution of the language over the years.
The first one, known as c-like initialization (because it is inherited from the C
language), it is achieved by appending an equal sign ‘=’ followed by the value to which
the variable is initialized:
For example, to declare a variable of type int called x and initialize it to a value of one
from the same moment it is declared, we can write:
int x = 1;
For example:
int x (0);
For example:
int x {0};
'z'
'p'
"Hello world"
"How do you do?"
The first two expressions represent single-character literals, and the next two
represent string literals composed of several characters. Notice that to represent a
single character, we enclose it between single quotes ('), and to express a string
(which generally consists of more than one character), we enclose the characters
between double quotes (").
Both single-character and string literals require quotation marks surrounding them to
distinguish them from possible variable identifiers or reserved keywords. Notice the
difference between these two expressions x and ‘x’.
Several string literals can be concatenated to form a single string literal simply by
separating them by one or more blank spaces, including tabs, newlines, and other
valid blank characters. For example:
Note how spaces within the quotes are part of the literal, while those outside them are
not. Some programmers also use a trick to include long string literals in multiple lines:
In C++, a backslash (\) at the end of line is considered a line-continuation character
that merges both that line and the next into a single line. Therefore the following code:
is equivalent to:
TYPE CASTING
A value in any of the built-in types we have seen so far can be converted (type-cast)
to any of the other types. The syntax is:
For example:
As shown by these examples, the built-in type identifiers can be used as type
operators. Type operators are unary (i.e., take one operand) and appear inside
brackets to the left of their operand. This is called explicit type conversion. When the
type name is just one word, an alternate notation may be used in which the brackets
appear around the operand:
In some cases, C++ also performs implicit type conversion. This happens when values
of different types are mixed in an expression. For example:
i = i + d; // means: i = int(double(i) + d)
CONTROL STRUCTURES
1- CONDITIONAL STRUCTURES
Conditional structures are statements used to control the flow of execution within a
C++ program. Some example of these statements include:
if (condition) statement
Where condition is the expression that is being evaluated. If this condition is true,
statement is executed. If it is false, statement is ignored (not executed) and the
program continues right after this conditional structure.
For example, the following code fragment prints x is 100 only if the value stored in the
x variable is indeed 100:
if (x == 100)
If we want more than a single statement to be executed in case that the condition is
true we can specify a block using braces { }:
if (x == 100){
We can additionally specify what we want to happen if the condition is not fulfilled by
using the keyword else. Conditional execution of code is implemented in C++ using
the if … else construct that looks like this:
if (conditional expression)
else
Another format of the if-else statement is the if else-if else statement. The conditional
expressions are evaluated from the top downward. As soon as a true condition is
found, the statement associated with it is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will be
executed. The final else often acts as a default condition; that is, if all other conditional
tests fail, then the last else statement is performed. If there is no final else and all other
conditions are false, then no action will take place. The syntax is:
if (conditional expression)
else
Nested if Statements
As the comments indicate, the final else is not associated with if (j) (even though it is
the closest if without an else), because it is not in the same block. Rather, the final
else is associated with if (i). The inner else is associated with if (k) because that is the
nearest if.
c. Switch Statements
The syntax of the switch statement is a bit peculiar. Its objective is to check several
possible constant values for an expression. Something similar to what we did at the
beginning of this section with the concatenation of several if and else if instructions.
The syntax is as follows:
switch (expression) {
case constant1:
group of statements 1;
break;
case constant2:
group of statements 2;
break;
.
.
.
default:
Finally, if the value of expression did not match any of the previously specified
constants (you can include as many case labels as values you want to check), the
program will execute the statements included after the default: label, if it exists (since
it is optional).
ITERATIVE STATEMENTS
They provide a way of repeating a statement while a condition holds. There are three
flavours of iteration in C++. We will pick each and every one of them for discussion.
a. While Loop
The while statement (also called while loop) provides a way of repeating an statement
while a condition holds. It is one of the three flavors of iteration in C++. The general
form of the while statement is:
First expression (called the loop condition) is evaluated. If the outcome is nonzero then
statement (called the loop body) is executed and the whole process is repeated.
Otherwise, the loop is terminated.
For example, suppose we wish to print the range of numbers from 1-8 using while
loops.This can be expressed as:
int main(){
int i= 1;
while (i<=8){
cout << i;
12345678
b. Do while loop
The do statement (also called do loop) is similar to the while statement, except that its
body is executed first and then the loop condition is examined. The general form of
the do statement is:
do
statement;
while (expression);
First statement is executed and then expression is evaluated. If the outcome of the
latter is nonzero then the whole process is repeated. Otherwise, the loop is terminated.
The do loop is less frequently used than the while loop. It is useful for situations where
we need the loop body to be executed at least once, regardless of the loop condition.
For example, suppose we wish to repeatedly read a value and print its square, and
stop when the value is zero. This can be expressed as the following loop:
cin >> n;
} while (n != 0);
Unlike the while loop, the do loop is never used in situations where it would have a
null body. Although a do loop with a null body would be equivalent to a similar while
loop, the latter is always preferred for its superior readability.
c. For Loop
The for statement is a more sophisticated loop in that it allows for an initialization
statement executed once (typically used to initialize a counter), checking for an exit
condition (typically using this counter), and performing an action at the end of every
loop (typically incrementing or modifying this counter).
DoSomeActivities;
The main function of the for loop is to repeat statement while condition remains true,
like the while loop. But in addition, the for loop provides specific locations to contain
an initialization statement and an increase statement. So this loop is specially
designed to perform a repetitive action with a counter which is initialized and increased
on each iteration.
2. Condition is checked. If it is true the loop continues, otherwise the loop ends and
statement is skipped (not executed).
4. finally, whatever is specified in the increase field is executed and the loop gets back
to step 2.
The for statement (also called for loop) is similar to the while statement, but has two
additional components: an expression which is evaluated only once before everything
else, and an expression which is evaluated once at the end of each iteration. The
general form of the for statement is:
The most common use of for loops is for situations where a variable is incremented or
decremented with every iteration of the loop. The following for loop, for example,
calculates the sum of all integers from 1 to 20.
#include <iostream>
int main(){
int sum = 0;
sum += i;
cout<< sum;
For loops with multiple loop variables are not unusual. In such cases, the comma
operator is used to separate their expressions:
//do something
ARRAYS
An array is a collection of variables of the same type that are referred to by a common
name. Arrays may have from one to several dimensions (1-dimensional array or multi-
dimensional arrays), although the one-dimensional array is the most common. Arrays
offer a convenient means of creating lists of related variables.
Types of Array
1. One-Dimensional Array
2. Multi-Dimensional Array.
One-Dimensional Arrays
A one-dimensional array (or a list, or a vector) is a group of related values with the
same data type that is stored using a group name. The group name is referred to as
the array name. The items in the list can be declared as a single unit and stored under
a common variable name called the array name.
type array_name[size];
For example, suppose that we would like to store five exam grades in an array, named
grade, the declaration statement will be:
int grade[5];
Other examples:
Array elements can be initialized within their declaration statements, enclosing their
values within braces. For example:
If the number of initializers is less than the declared number of elements listed in
square brackets, the initializers are applied starting with array element zero. For
example:
A unique feature of initializers is that the size of an array may be omitted when the
initializing values are included in the declaration statement. For example:
In any point of a program in which an array is visible, we can access the value of any
of its elements individually as if it was a normal variable, thus being able to both read
and modify its value. The format is as simple as:
data_type name[index]
For example:
int billy[5];
For example, to store the value 75 in the third element of billy, we could write the
following statement:
billy[2] = 75;
and, for example, to pass the value of the third element of billy to a variable called a,
we could write:
a = billy[2];
Therefore, the expression billy[2] is for all purposes like a variable of type int.
Notice that the third element of billy is specified billy[2], since the first one is billy[0],
the second one is billy[1], and therefore, the third one is billy[2]. By this same reason,
its last element is billy[4]. Therefore, if we write billy[5], we would be accessing the
sixth element of billy and therefore exceeding the size of the array.
It is important to be able to clearly distinguish between the two uses that brackets[
]have related to arrays. They perform two different tasks: one is to specify the size of
arrays when they are declared; and the second one is to specify indices for concrete
array elements.
If you read carefully, you will see that a type specifier always precedes a variable or
array declaration, while it never precedes an access.
// arrays example
#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
Multi-dimensional Array
C++ allows multidimensional arrays. The simplest form of the multidimensional array
is the two-dimensional array. A two-dimensional array is, in essence, a list of one-
dimensional arrays. To declare a two-dimensional integer array twoD of size 10 by 20,
you would write:
Pay careful attention to the declaration. Unlike some other computer languages, which
use commas to separate the array dimensions, C++ places each dimension in its own
set of brackets. Similarly, to access an element, specify the indices within their own
set of brackets.
In the next example, a two-dimensional array is loaded with the numbers 1 through
12.
Two-dimensional arrays are stored in a row-column matrix, where the first index
indicates the row and the second indicates the column. This means that when array
elements are accessed in the order in which they are actually stored in memory, the
right index changes faster than the left. You should remember that storage for all array
elements is determined at compile time. Also, the memory used to hold an array is
required the entire time that the array is in existence.