You are on page 1of 245

Kkkkllklkl;lk;lk;lk;lk;lk;kl

Saif’s Lecture Notes on

Programming
with
C++
PROCEDURAL PROGRAMMING &
OBJECT ORIENTED PROGRAMMING

SAIF BASHAR

October 2019 update


This is an explanatory book for beginners
about the basic concepts of C++
programming language, Part 1 discuss
the basic concepts of procedural
programming and structured programs,
Part 2 is about object-oriented
programming for more information and
resources visit my website at: saif.io

Note: this book is under development and continuous


improvements, you can send me your thoughts and
suggestions or if you find some ambiguous topics that needs
more clarification, you can also report about typos or
programming mistakes, you can email me at:
110118@uotechnology.edu.iq with my thanks and
appreciations
To the students of today, programmers of tomorrow
Chapter 00
Notes
0.1 General Notes
0.2 Working Environment
0.3 Caution
0.4 Symbols & Colors
0.5 General Table of Contents

Part 1
s a i f . i o
CHAPTER 00 Saif.io

0.1 General Notess


This book is for beginners in programming it doesn’t assume any
previous experience in programming in order to read it, but you need the
basic information about computers in general, the book is written for the
first stage university students for computer science major or anyone who
want to learn the basics of programming and to dive in the massive
programming world.

The book contains two parts, the first part will gradually explain the
fundamental concepts of structured programming using the C/C++
language, part two will enter the world of object-oriented programming
(the modern style of programming) which is usually taught at the second
stage in computer sciences colleges in Iraq, this book is dedicated to
everyone who wants to know what programming is all about.

0.2 Working Environment


There are many working environments or IDEs to work with, The
working environment I used in executing all the examples of this book
called CodeBlocks the current version is 17.12, it’s an up to date
environment that is updated and improved regularly the number 17
indicate the year which is 2017 and the number 12 indicates the month the
version was released, this environment is free, lightweight and cross
platform which means that you can find version that works on all the major
operating systems such as Windows, Linux and MacOS you can find the
Windows version in my website, follow this link:
saif.io/programs.html

You can find other versions for other platforms at their official website at:
http://www.codeblocks.org

©Saif Bashar 2019


CHAPTER 00 Saif.io

Make sure the version you download contains the GCC compiler, the
version I provided in my website contains the GCC compiler version 6.2.0.
All the programs in this book are executed using CodeBlocks 17.12 on a
laptop with these specifications:

✓ CPU Intel Core i3 1.9 GHz


✓ RAM DDR3 8 GB
✓ OS Windows 10 Pro 64 bit

Before we start our journey, you need to install the CodeBlocks IDE, you
can watch the video in the link below to show you the steps required for
installing and configuring this environment to get you ready to write your
programs and creating your C++ projects:

Video lecture: Installing CodeBlocks IDE


https://youtu.be/PWfQwDdGpVw

There is however a nice website that provide online compilers for most of
the famous programming languages, this site makes you write, execute
and share programs with your friends without installing anything on your
machine. The website is https://repl.it but make sure when you choose C++
select the C++11 the version that support all the new features that we will
learn later in this book.

©Saif Bashar 2019


CHAPTER 00 Saif.io

0.3 Caution
Before we begin, you have to know something important, that you
cannot learn programming or be a programmer by only reading books or
listening to lectures, you have to practice programming by writing
programs and fixing errors that occurs, in a matter of fact you will spend
more time fixing errors than writing code, you have to work on all the
examples of this book and solve the exercises and challenges at the end
of each chapter, most importantly make sure that your programs are
working correctly and giving the desired output because making the
program run is one thing and making it give correct results is another.

“Learning programming is like learning how to play on a musical


instrument, the only way to be proficient is by continuous practice “

©Saif Bashar 2019


CHAPTER 00 Saif.io

0.4 Symbols & Colors


There are many symbols and colors used in this book explained as
follows:

This symbol to warn you about programming


errors that you might fall in to

This symbol for programming instructions and


statements, that you should run

This symbol for important notes, you should


remember

This symbol for rules and programming syntax

This symbol for a video content

The code written in this book followed the default color coding scheme of
the CodeBlocks IDE, to make the code more readable, the following colors
used and described in the following table:

Identifiers
Keywords
Special Functions
Characters
Numbers
Comments
Operators
Strings

©Saif Bashar 2019


CHAPTER 00 Saif.io

0.5 General Table of Contents

Part 1
Chapter 00 – Notes 00 – 04
Chapter 01 – Introduction 05 – 17
Chapter 02 – Essentials 18 – 42
Chapter 03 – Logical Decisions 43 – 61
Chapter 04 – Loops 62 – 78
Chapter 05 – Functions 79 – 106
Chapter 06 – Arrays 107 – 121
Chapter 07 – Strings 122 – 130
Chapter 08 – Structures 131 – 138
Chapter 09 – Pointers 139 – 143
Chapter 10 – Files 144 – 152

Part 2
Chapter 11 – Classes & Objects 153 – 172
Chapter 12 – Friends 173 – 180
Chapter 13 – Pointers and Arrays of Objects 181 – 188
Chapter 14 – Operators Overloading 189 – 198
Chapter 15 – Inheritance 199 – 217
Chapter 16 – Templates 218 – 224
Abbreviations

©Saif Bashar 2019


Chapter 01
Introduction
1.1 Overview on C/C++
1.2 Important Terms
1.3 The Way to be a Good Programmer
1.4 Main Parts of C++ Program
1.5 Comments
1.6 Stages of Writing & Executing C++ Programs
1.7 Common Error Types
Exercises 1

s a i f . i o
CHAPTER 01 Saif.io

1.1 Overview on C/C++


Programming languages are the languages that are used by
humans to talk to computers to make them do what we want, in
order for a computer to understand us we have to use a language
the computer understands. Computers are electronic devices they
understand the language of electricity I mean the existence of
electrical charge in its complex circuits; this charge is represented by
two states on/off or zero/one. this language is called the machine
language which is represented by the binary number system so it is
also called binary language. So, computers understand binary
language very well, but we as humans it is impractical to write
programs in binary language because it is low level and we have to
memorize every instruction binary code which is impractical and
tedious.

Companies and computer scientists started to invent programming


languages that are closer to the human level high level to make
programming easy and more productive, since the computer
revolution thousands of programming languages are written some of
them are no longer been used today and some of them are still in
use and new programming languages are still emerging every
couple of years.

C programming language is considered one of the old


and still widely used language by many companies
and programmers in various areas of technology, the
language was written in the early seventies by the
computer scientist Dennis Ritchie it was called C
because it was derived from the B language and other
languages like COBOL and Simula, B language was written by Ken
Thombson who is Dennis’s friend as they were working at Bell
laboratories, Ken wrote the famous UNIX operating system in C
language.

The C language updated several times from 1977 to 1979 and the
standard release was in the mid-eighties and it was called ANSI C,

©Saif Bashar 2019


CHAPTER 01 Saif.io

the language was widely accepted and adopted by many


companies and programmers.

The C programming language considered a general-purpose


language and a procedural language that the program consists of a
number of procedures called functions that perform a specific task
and a main function that drive the program execution.

The biggest update that happened to the C language


is in 1979 when the computer scientist Bjarne Stroustrup
the other friend of Dennis, added the concept of
objects and classes and applied the object-oriented
programming style with many new features he called
the experimental release C with classes then the name
was changed to C++, I dedicated part two of this book to talk about
OOP with C++.

C++ also had gone through several updates and releases; every
release contains several upgrades adding new features removing
some and so on.

✓ ISO C++ in 1997


✓ ISO C++ in 1998
✓ ISO C++ in 2003
✓ ISO C++ in 2006
✓ ISO C++11 in 2011
✓ ISO C++14 in 2014
✓ ISO C++17 in 2017

The work in progress on the 2020 release.

©Saif Bashar 2019


CHAPTER 01 Saif.io

The main features that Bjarne added to the C language were:

1- Support the OOP programming style with all its advance


features like Encapsulation, Inheritance, Polymorphism,
Operator Overloading and other features like Virtual Functions
and Exception Handling … etc. we will discuss those features in
part two of the book.

2- Added the concept of Class Templates to deal with data.

What are the reasons that made C/C++ programming languages


powerful languages and widely used today? Here is some:

1- The C language became the base language for other


languages that are derived from it like php for backend web
development, Java, Python, Objective-C, C# and other many
languages, it also used in building the Oracle database, the
UNIX, Linux and Mac operating systems and parts of the
Windows operating system.

2- The C programming language is considered by some authors a


mid-level language because it contains features that allow the
programmer to use it either on high level or on a low level. it
provides the tools to let the programmer work directly with
memory and device drivers it also supports pointers, and this will
make programmers write very fast and efficient programs.

3- It is considered a cross platform language that works on any


platform or operating system unlike languages like Visual Basic
which works under the Windows environment only, you still
need to install a compiler for each platform.

4- The C programming language has a small number of keywords


which make the learning process easier.

5- It supports a huge number of libraries in various topics.

©Saif Bashar 2019


CHAPTER 01 Saif.io

C++ are not the easiest programming language to learn but learning
it and master all its concepts will make it easy to learn any other
programming language.

Video lecture: Introduction


https://youtu.be/huWwibFczeE

1.2 Important Terms


Every science has its own terminologies, programming also has its
own terms that you need to know and keep in mind:

1- Instruction: an instruction is the single command that perform a


specific function like adding two numbers for example, the
instructions are stored in memory and executed by the CPU.

2- Program: a program is a series of instructions written in a


programming language that solve a specific problem, the
person who write programs that solve problems is called a
programmer.

3- Algorithm: an algorithm is a series of steps written in plain English


that describe the solution steps for a particular problem.

4- Compiler: a compiler is program that acts as a translator that


translates the high-level language C/C++ to the low-level
language binary language that the computer understands.

5- Programming Language: it is the tool used by a programmer to


write programs, it consists mainly of Keywords and syntax.

6- Keywords: words that have a special meaning in programming


languages these words are preserved for special and have a
specific function.

©Saif Bashar 2019


CHAPTER 01 Saif.io

In this book we will talk about most of the C/C++ keywords, as


new keywords always added to newer releases:

new delete int char


class float double
namespace bool for if
using private else switch
public case default
protected while do
this template break
operator continue
catch try struct auto
inline friend const enum
throw virtual extern goto
true false long short
signed
unsigned
sizeof return
union static
register
typedef void
volatile

Figure 1.1 C/C++ Keywords

C++ language is a super set of C language it supports all the


keywords of C language and more.

7- Syntax: it is the set of rules that every programming language


have that applied on keywords to perform a specific operation,
syntax is the language structure, it is like grammar to the English
language.

Video lecture: Terminology


https://youtu.be/IxktJ5dZBqM

©Saif Bashar 2019


CHAPTER 01 Saif.io

1.3 The Way to be a Good Programmer


Before I start to explain to you the keywords and syntax of the
C++ language and writing code, I want to tell you something very
important, the thing is called logical thinking, in order for you to
become a good programmer is not to have a full knowledge of the
programming language keywords and syntax, but you have to think
logically, there are a lot of computer science students that
understand every concept in the language that they study and can
memorize every instruction but still can’t write useful programs to
solve simple problems.

The reason behind this is that they learned programming the wrong
way, learning programming is not about memorizing instructions and
programs, it’s about training your brain to think logically by breaking
down any problem into a series of simple logical steps, every step
leads to the other until you reach the solution, this logical thinking
ability can be developed by practicing programming and fixing
errors and always trying to solve the problems on your own way, not
by memorizing somebody’s else solution.

You can look at someone’s else solution after you solve the problem
yourself to benefit from other ideas and learn new ways beside your
own thinking, the fun thing about programming is that everybody
can solve a particular problem in his/her own way.

So, any problem you face try to give it a good thinking and write it
down as an algorithm with simple easy steps until you reach to the
solution or something close to the desired solution as you always can
repeat the process until you are satisfied with the outcome.

©Saif Bashar 2019


CHAPTER 01 Saif.io

1.4 Main Parts of C++ Program


It’s time for us to learn some code, in this section I will explain
the main parts of every C++ program, don’t worry if you don’t
understand some of the code lines, as they will become clear in the
upcoming chapters.

Every program in C++ has a


function called main which
Program 1.1
represent the starting point of
1 main () { the program, I will explain what
2 } a function is in chapter five in
details.

The main function consists of:

1- The function name which is main


2- A pair of parenthesis ( ) for taking input into the function
3- A pair of curly braces { } indicate the start and the end of the
function
4- The function body between the curly braces that contain the
code that will be executed when the main function is running.

Program 1.1 is an empty program that do nothing, but you can


execute it, you will see the output screen flashes, this mean that the
main function started and ended quickly because there is no code
in it to execute, this is the shortest program that you will ever write.

It’s a programmer’s tradition in


the programming world to
Program 1.2
start learning a language
1 #include<iostream>
syntax by writing a program
2 using namespace std;
3 that prints a sentence on the
4 main ( ) { screen in order to get you
5 cout<<"Hello World!"; familiar with the main parts of
6 }
the program, this program is

©Saif Bashar 2019


CHAPTER 01 Saif.io

called Hello World, because it simply prints the sentence Hello


World! on the output screen.

If you wrote the program exactly as it is, then executed the program
you will see the sentence Hello World! on the output screen, you
can see that the program printed the characters that are
surrounded by double quotes, we call this series of characters a
string.

As I mentioned earlier that C++ language contains many functions


and libraries, in Program 1.2 I used a function named cout which
mean console out, we use it to print things on the computer screen
and this function belongs to a library called iostream which mean
input output stream, so in order to use a function in a library we have
to include that library in our program first, as you can see in Line 1
and Line 2 in Program 1.2.

Note that the include keyword preceded with a hash sign #, the
hash sign called the preprocessor directive used whenever we want
to include some libraries into our programs or when we want to
replace pieces of code in the program, we will talk about
preprocessor directive later in this book.

The cout function needs to use the insertion operator << that looks
like an arrow passing the string to the cout function, see Line 5, The
cout function and it’s operator and the string all of these parts are
called a statement, and you should always remember all statements
in C/C++ language ends with a semi colon ( ; ) it’s the way the
compiler knows that the statement ends here, try to delete the semi
colon and run the program you will see an error message and the
program will not run, it is a common mistake for new programmers to
forget the semi colon at the end of statements.

©Saif Bashar 2019


CHAPTER 01 Saif.io

There is another function that we can use with the cout function also
belongs to the iostream library, the function is endl which mean end
line it produces a new line in the output screen. execute Program 1.3
and see the result, you see that each string is printed on a single line.

Program 1.3
1 #include<iostream>
2 using namespace std;
3
4 main ( ) {
5 cout<< "I am a programmer" << endl;
6 cout<< "I love coding";
7 }

1.5 Comments
Comments are descriptive messages written by programmers to
help them explain what a certain line of code is doing. Comments
are very helpful if a group of programmers are working on the same
project or other programmers that will read your code in the future to
understand what you were doing.

Comments are ignored by the compiler because they are not part
of the language syntax. There are two ways to write comments in
C++:

1- C Style Comments: useful in writing multiline comments it starts


with symbols / * and ends with the symbols * / everything in
between is considered a comment.

2- C++ Style Comments: used in a single line comment it starts with


the symbols //

©Saif Bashar 2019


CHAPTER 01 Saif.io

Program 1.4
1 /* this is my first program
2 Learning C++ is so much fun */
3 #include<iostream>
4 using namespace std; //discussed later
5 main ( ) {
6 cout<<"I am a programmer"<<endl;
7 cout<<"I love coding";
8 }
9

As you see in Line 1 and Line 2 the C style comment, and at Line 4 I
used the C++ style comment. Make sure to use comments in your
programs especially above the main function describing what your
program trying to do. You will find it useful when you read your
programs in the future.

Video lecture: Hello World


https://youtu.be/Gwt1jhgRegw

1.6 Stages of Writing & Executing C/C++ Programs


There are several main stages for your programs go through until
you see the results on the output screen, these stages are:

1- Editing: the stage of writing your program using an editor or an


IDE, this stage goes through a series of corrections and
rethinking of the code logic by the programmer, the file you
write the code in is called a source file, the code inside it is
called source code, this file stored in the hard disk with .c or
.cpp extensions.

©Saif Bashar 2019


CHAPTER 01 Saif.io

2- Pre-Processing: the stage where the preprocessor does its work


by including all the libraries and files that you included in your
source code.

3- Compiling: the stage where the source code translated to


binary language and a new file is created called the object file
with the extension of .obj or .o in some compilers.

4- Linking: the stage where the linker links the source code with
the code in the included files and libraries, and produce an
executable file with the extension .exe in Windows
environment.

5- Loading: this stage where the program is loaded to the main


memory from the hard disk.

6- Executing: the stage of executing the program in memory by


the CPU.

Figure 1.2 Stages of C/C++ programs

©Saif Bashar 2019


CHAPTER 01 Saif.io

Editor

Prepocessor

Compiler

Linker

Loader

Execution

Figure 1.3 Stages of C/C++ programs

1.7 Common Error Types


The most common errors a programmer usually does are:

Common Error Types

1- Compile Time Errors: the errors that occur at the


editing stage when you write your code, some of
them are simple typos other are syntax errors.

2- Runtime Errors: the errors that occur at runtime,


these types of errors are hard to catch, for example
errors like dividing by zero or the overflow error and
many others.

©Saif Bashar 2019


CHAPTER 01 Saif.io

Exercises 1
Q1: Why it’s called C language?

Q2: Write an algorithm that add two numbers

Q3: Write an algorithm that average five numbers

Q4: Why C/C++ languages are still widely used today?

Q5: List famous programs or systems programmed by C or C++


languages other than was mentioned before?

Q6: Describe the C/C++ programs execution stages?

Q7: Why C language can produce fast efficient programs?

Q8: Why we need a compiler?

Q9: Why does some authors consider C languages a mid-level


language?

©Saif Bashar 2019


Chapter 02
Essentials
2.1 Identifiers & Variables
2.2 Primitive Data Types
2.3 Storage Specifiers
2.4 Arithmetic Operators
2.5 Type Conversions
2.6 Precedence Law
Exercises 2

s a i f . i o
CHAPTER 02 Saif.io

2.1 Identifiers & Variables


An identifier is a name given by the programmer to define new
elements in the program like variables, functions, arrays, structures,
classes and so on.

A variable has a name that represent a location in memory, we can


store data in that location, this location has many main things:

1- Identifier: a name given by the programmer.

2- Address: addresses is by design built in the memory coded in


hexa-decimal number system.

3- Type: type of the data that will be stored in this location


determined by the programmer.

4- Value: the value depends on the type of the variable given


either by assignment or using the cin function. If you do not
provide a value to a variable it will take a random value.

5- Size: the variable size specified by the variable type, it depends


on the language design and the computer architecture.

Value
Name Type

Address Variable Size

Figure 1.2 things related to variables

©Saif Bashar 2019


CHAPTER 02 Saif.io

Note that in C/C++ you should define (declare) a variable before


you can use it in your program, defining a variable means give it an
appropriate identifier and a data type, this is why C/C++ called a
strongly typed language. Other languages are called weak typed
language like JavaScript and php which means that you don’t have
to specify a type for the variable.

Naming an identifier have several conditions:

1- Use only English letters

2- Don’t start with a number, but it can contain numbers

3- Don’t use special symbols except the underscore _ is allowed


because it make long identifiers more readable. You cannot
use spaces because a space also considered a special
character

4- Don’t use reserved keywords or function names already


defined

5- Don’t use a used name in the same scope

Examples on allowed and not allowed identifiers:

Identifiers Examples

Allowed:
my_number, x1, myNumber, pi, counter, INT, fi

Not Allowed:

-myAge, 4ever, my number, cout, for, int

©Saif Bashar 2019


CHAPTER 02 Saif.io

You should know also that C/C++ are case sensitive languages
which means if we give a name to a variable like mynumber this is
not the same as Mynumber and also not the same as myNumber
because the letter cases differ, C/C++ treat these names as three
separate variables.

A good practice is to use descriptive identifiers names, always give


your identifiers names that reflect their purpose for example for a
variable that store the student average you can name it stdAverage
it is better than naming it v, for a function that calculate the
maximum student score you can name it stdMaxScore better than
just max. programmers love to use camel case notation in naming
their identifiers, it makes long names more readable here are some
examples: stdAverage, stdAge, totalSalary, oopMark, printInfo and so
on.

Values can be given to variables in two ways either by direct


assignment in edit time or by using the cin function in runtime.

Syntax of assigning values to variables

variable = value;

variable = expression;

cin>>variable;

Note that the assignment operator = is used to pass the value (or the
expression result) at its left and store it in the variable on the right. The
assignment operator is not the same as the equal sign in
mathematics.

©Saif Bashar 2019


CHAPTER 02 Saif.io

Also note that the cin function use its own operator >> the extraction
operator for each variable you want to read.

Video lecture: Variables


https://youtu.be/l5R44bPxcL4

2.2 Primitive Data Types


As we learned before we have to define or declare a
variable before we start using it in our program, defining a variable
means giving it an acceptable identifier name and a data type, the
main data types in C++ are:

1- int: used for integer numbers positive, zero and negative


numbers.

2- float: used for decimal numbers positive and negative with less
precision.

3- double: used for decimal numbers positive and negative with


more precision.

4- char: used for a single character, surrounded by a single quote.

5- string: used for a group of characters surrounded by double


quotes.

6- bool: used for Boolean values either true/false or 0/1.

©Saif Bashar 2019


CHAPTER 02 Saif.io

The int data type used to represent integers or whole numbers


without fractions

Program 2.1
1 // working with integer variables
2 #include<iostream>
3 using namespace std;
4 main () {
5 int a, b, c;
6 a = 133;
7 b = a + 44;
8 cout<<"Enter a value for C:";
9 cin>>c;
10 cout<<"You have three values:";
11 cout<<endl<<a<<endl<<b<<endl<<c;
12 }

Program 2.1, in Line 5 I declared three variables of type integer as


you see you can declare as many variables as you need in a single
line separating them by the comma operator ( , ) then end the
declaration statement with a semi colon. in Line 6 an assignment
statement using the assignment operator to assign the value 133 to
the variable a.

Line 7 another assignment statement but before the assignment


happens an expression at the right-hand side need to be evaluated
first, so the processor evaluates the expression a + 44 the addition
operation which will produce 177 then the value 177 is assigned to
the variable b.

Line 8 is just a prompt that prints a message to the user so he/she can
know there is a reading operation is coming next, prompts are very
important it makes your program clear and understandable by the
person who will use it.

©Saif Bashar 2019


CHAPTER 02 Saif.io

Line 9 is another assignment statement but now is by using the read


function cin with its operator the extraction operator >> then the
name of the variable we want to store the value given by the user in
this case the variable c. (let’s assume the user will type 55).

Line 10 another prompt to explain the output to the user, Line 11 will
print the values of our three variables note that I added the endl
function so that each value will appear on a single line, so the output
of our program will be:

You have three values:


133
177
55

A very important thing about data types is their size in memory, the
size means the number of bytes allocated for a variable in memory,
the size differs from language to language, from compiler to compile
and sometimes in the same language a difference can be found in
two releases, in the environment am working on now the size for int is
4 bytes.

©Saif Bashar 2019


CHAPTER 02 Saif.io

There is an operator used for finding the size of things, you give this
operator a data type or a variable and it will tell you the number of
bytes allocated, the operator is sizeof you can use it like Program 2.2
to check your variable sizes. (note that I left the main parts of the
programs for you to complete)

Program 2.2
1 // WOW this is a long statement
2 cout<<"int "<<sizeof(int)<<endl
3 <<"float "<<sizeof(float)<<endl
4 <<"double "<<sizeof(double)<<endl
5 <<"char "<<sizeof(char)<<endl
6 <<"long double "<<sizeof(long double)<<endl
7 <<"bool "<<sizeof(bool)<<endl
8 <<"long long "<<sizeof(long long)<<endl
9 <<"short "<<sizeof(short);

I got the following results on the environment am working on, maybe


you will see different values.

int 4
float 4
double 8
char 1
long double 12
bool 1
long long 8
short 2

So, why we bother ourselves knowing about variable sizes in our


program? Because it affects the results of our program. A variable
size will determine its range and by range, I mean the range of
values the variable can represent, knowing the size will let us find the
variable limits.

©Saif Bashar 2019


CHAPTER 02 Saif.io

Before we learn how to calculate ranges we should now the basic


computer storage units:

Storage Unit Number of Bits


Bit zero or one
Byte 8 bits
Word 16 bits
Double Word 32 bits
Quad Word 64 bits

Now, if we know the data type size we can calculate its range, lets
calculate the range of the int data type:

✓ The size of int data type is 4 bytes = 32 bits


✓ The numbers that can be represented in 32 bits are 2 32 =
4,294,967,296 number
✓ We know integers include positive and negative numbers, so
we divide that big number by two to get 2,147,483,648 number
in each direction (positive and negative)

So, the largest number is positive 2,147,483,647 and the smallest


number is negative 2,147,483,648, now when we try to add two
integer numbers let’s say 2000000000 + 2000000000 we will not get 4
billion but we will get a negative value. because 4 billion cannot be
represented in an integer variable, we get a negative value
because the number will round on itself to reach negative values
which is clearly a wrong answer.

The scenario above demonstrated the type overflow runtime error


when a program tries to fit some large values into a small memory
space. This considered a hard error to find and it can destroy the
program results.

Program 2.2 contains new keywords short, long these are not data
types, they are called modifiers they modify the data type size, so a
short or short int will take 2 bytes while long int or int will take 4 bytes.

©Saif Bashar 2019


CHAPTER 02 Saif.io

You might wonder why would I use short data type, when I can use
just int? I will tell you that a good programmer always takes a good
care for memory consumption by his/her program. so, for example
when you have a variable to represent a person’s age you better
use the short data type because you don’t need large values and
waste memory the short range will be from 32767 to -32768. Programs
that use less memory are faster than programs that use more
memory.

Solving the issue that we faced earlier to get the 4 billion correctly
we can use long long modifier which takes 8 bytes that can cover
the 4 billion.

We also can take only the positive part of a number by using the
unsigned modifier, so if you defined a variable as unsigned int it will
take the range from 0 to 65536, we don’t have to use the signed
modifier because it is implied in the int data type, we can use
unsigned integers for variables that represent age, student’s marks,
salary, lengths, distances and so on, while we can use signed
integers representing temperatures, variables for mathematical
calculations that involve positive and negative numbers and so on.

The float, double data types these data types are used to declare
variables that represent decimals, the numbers that has fractions,
numbers with the floating point, in mathematics they are called the
rational numbers.

We use the float or double keywords for decimal variables, they differ
in size and range, double mean more places after the decimal point,
we can also use long double for more precise numbers.

©Saif Bashar 2019


CHAPTER 02 Saif.io

The range of the float type is from 3.4e+38 to -3.4e-38 and the
double type from 1.7e+308 to -1.7e-308, notice the language accept
the scientific notation these numbers mean

38 -38
3.4e38 = 3.4*10 -3.4e-38 = -3.4*10

308 -1.7e-308 = -1.7*10


-308
1.7e308 = 1.7*10

Note that we should use the dot as a decimal point not the comma,
the comma is an operator use to separate variables. This is a decimal
number 1.5 and this 1,5 is wrong.

The char data type This data type is used to store a single character,
in programming when we say character we mean all the small
letters, all the capital letter, the digits from zero to nine and all the
special symbols on the keyboard.

C/C++ languages surround the character with a single quotation


mark, remember that double quotation marks are used for strings.

The char data type uses only one byte in memory for each
character, also you should know that all characters are represented
by a numerical code system called the ASCII code, visit this website
http://www.asciitable.com to look at the whole table of the
numerical values for each character. You can memorize the
character ‘a’ has the ASCII of 97 and the character ‘A’ has the ASCII
of 65, or you can use a built-in function that can find the ASCII code
for a given character the function is int(), there is another function
that do the opposite, char() function takes an integer and return it’s
equivalent character, try to check the output of the following code:

int a = 65;
char b = ‘F’;
cout<<char(a)<<endl<<int(b);

©Saif Bashar 2019


CHAPTER 02 Saif.io

The string data type This data type used for series of characters like
names, addresses, messages and so on, in the old versions of the
language this data type was not exist then it was added on later
releases at first you had to add the string library using
#include<string.h> but now you don’t have to, they moved it to
the standard library of the language.

The size reserved for this type is depended on the number of


characters a string has, each character reserve one byte as I
mentioned above, so for a string with four letters like “saif” it will
reserve 5 bytes. I will tell you why 5 in Chapter 7 when we discuss
strings.

The bool data type This data type is used to represent only two
values either true or false, as the false equals the number zero and
every other number is considered true but usually true takes the
value of one, this data type is useful in logical operations as we will
see later on.

The name bool came from the mathematician George Boole who
wrote the principals of Boolean Algebra, that the work of the logical
gates in the computer depends on.

Example to illustrate working with variables of different data types.

Program 2.3
1 // working with different data types
2 #include<iostream>
3 using namespace std;
4 main () {
5 const float pi = 3.14;
6 string name = "saif";
7 char c = ’S’;
8 bool t = true;
9 cout<<name<<endl<<pi<<endl<<c<<endl<<t;
10s }

©Saif Bashar 2019


CHAPTER 02 Saif.io

Program 2.3 will produce the following output:

saif
3.14
S
1

The const keyword in Line 5 is used to make variables act as


constants, which mean its value cannot be change in the program,
there are number of mathematical constants we can use this
keyword to protect them from erroneous altering, note that you
have to give a value for the constant variable at the declaration
statement. The opposite to the const keyword is the volatile keyword
which is the default case for variables, variables are meant to store
changing values during the program execution. The volatile keyword
is implied and we don’t have to write it when we declare a variable.

There is another keyword used to declare list of variables represented


by numerical values the keyword is enum short of enumeration,
usually used to make your program more readable and it combine
things of the same nature like names of the week days, names of the
months or name of the four seasons and so on.

enum season {fall, spring, summer, winter};


season s1, s2;
s1 = fall;
s2 = spring;

The members of the enumeration season will take the numerical


values fall = 0, spring = 1, summer = 2 and winter = 3 but you can
change that in the declaration and give it the numbers you want,
like the following example:

enum coin {cent=1, nickel=5, dime=10, quarter=25,


half=50, dollar=100};

Video lecture: Basic Data Types Video lecture: Notes on Data Types
https://youtu.be/JRq6Ga1n_gU https://youtu.be/p9hcOeW9Y3Y

©Saif Bashar 2019


CHAPTER 02 Saif.io

2.3 Storage Specifiers


The C++ language provide keywords that are used to specify how
a certain variable is stored and where, it gives the programmer more
control on variables:

1- The auto keyword: it specifies the default choice for variables,


automatic variables are created in main memory at the
declaration statement and deleted at the end of the scope the
variable lives in. when we declare a variable by giving it a
name and a data type we don’t need to add the storage
specifier auto because it is assumed by default. (note the
functionality of the keyword auto has been changed in later
releases of the language).

2- The register keyword: it will specify the CPU registers as a


storage location for a variable. This will be useful for frequently
used variables to make them closer to the CPU which will make
our programs faster.

register int i = 0;
auto int age = 30; //the same as int age = 30

There are other keywords used to control variables like (static, extern)
I will talk about them in the upcoming chapters.

©Saif Bashar 2019


CHAPTER 02 Saif.io

2.4 Arithmetic Operators


The word Operator in programming world means a symbol or
more than one symbol that have a specific operation to perform,
C++ is a very rich language in operators we have seen some
operators like the insertion and extraction operators, the comma
operator, the assignment operator and others, we can categorize
operators and group them according to the nature of the operations
they perform and I will start with arithmetic operators.

Arithmetic operators are very familiar to us, they are the same old
simple arithmetic operations that we learned in elementary school,
described in the following table:

Arithmetic Operators
Operator Operation Example
* Multiplication c=a*b;
/ Division c=a/b;
% Remainder c=a%b;
+ Addition c=a+b;
- Subtraction (Negative Sign) c=a-b; d=-c;

Be careful when you use the division operator, if you give it two
integers it will do an integer division and truncate the fraction part,
for example if you do this:

int a = 1;
int b = 2;
float c = a / b;
cout << c;

You will get zero as an output because ½ is 0.5 and the integer
division will omit the .5, fixing this problem use floats in division

float a = 1;
float b = 2;
float c = a / b;
cout << c;

©Saif Bashar 2019


CHAPTER 02 Saif.io

Also note that the remainder operator only works with integers it
doesn’t work with float or double operands.

Make Examples

Try to make examples for yourself to test the arithmetic


operators and see if you will get the correct results.

Other Arithmetic Operators


There are other operators that are used in arithmetic operations and
considered a shortcut to make the programmer write less code,
these operators or shortcuts are listed in the following table:

Shortcut Arithmetic Operation


a++; a=a+1;
++a; a=a+1;
a--; a=a-1;
--a; a=a-1;
a+=b; a=a+b;
a-=b; a=a-b;
a*=b; a=a*b;
a/=b; a=a/b;
a%=b; a=a%b;

The top four rows in the table above describe two very commonly
used operators in programming and they are the increment and
decrement operators, the increment operator add one to the old
value of the variable and store the new value in the same variable,
the decrement operator subtract one from the old value of the
variable and store the new value in the same variable.

©Saif Bashar 2019


CHAPTER 02 Saif.io

The increment and decrement operators have two ways in using


them:

1- Prefix: when the increment or the decrement operator comes


before the variable as the following code will print 51 51:

int a=50, b;
b = ++a;
cout<<b<<" "<<a;

This statement b = ++a; first tries to solve the right-hand side of


the expression which is ++a and since it is a prefix notation it will
add one to the value of the variable a to become 51, then this
value is assigned to the variable b to become also 51.

2- Postfix: when the increment or the decrement operator comes


after the variable as the following code will print 50 51.

int a=50, b;
b = a++;
cout<<b<<" "<<a;

This statement b = a++; first tries to solve the right-hand side of


the expression which is a++ and since it is a postfix notation it will
assign the current value of a which is 50 to the variable b, then
add one to the value of the variable a to become 51.

Try to check the decrement operator in these two notations.

Note that if you use the increment or the decrement operators on a


single statement not as an expression it will make no difference
whether you use prefix or postfix notation since it will always add or
subtract one from the variable’s value, the following code will print
51 in both notations.

int a=50;
++a;
cout<<a;

©Saif Bashar 2019


CHAPTER 02 Saif.io

The rest of the shortcuts when you write:


a+=10; // or a=a+10

it means add 10 to the old value of a and store the new value in a,
the same goes for -=, *=, /= and %=

Video lecture: Arithmetic Operators


https://youtu.be/vRtV12AjIFw

2.5 Type Conversions


We learned that every variable should have a type that is
specified in the declaration statement, the question now is can we
change this data type later in the program? the answer is simply yes.
There are various ways to convert a variable type to another,
specific functions are designed to change a variable form one type
to another but I will discuss these functions after chapter five when
we study functions in details.

There is a method called Type Casting you can use to change a


value to another type check the code below:

int a=1, b=2;


float c = (float) a/b;
cout<<c;

As we saw before the code float c = a/b; will produce an


integer result, we can use the type casting method to force the
integer division return a float number and the result will be 0.5 as we
expect, note we didn’t change the types of the variables a and b.

©Saif Bashar 2019


CHAPTER 02 Saif.io

There is also implicit type conversion happens when different data


types are mixed in an expression for example:

float c = 1;
int d = 5.6;

The integer 1 will implicitly converted to 1.0, also the number 5.6 will
be implicitly converted to integer 5.

2.6 Precedence Law


The arithmetic operators are governed by a law called the
precedence law, which is a law that give priorities to some
operations over another, for example if we have the following
expression what it should produce?

int a= 2 + 3 * 4;

Well if you say 20 you are wrong, the expression above will produce
14 because the precedence law give priority to multiplication over
addition, so the multiplication 3*4 then the addition 12+2.

The arithmetic operators’ precedencies can be explained in the


following table (higher row means higher precedence)

Operator Operation
() Parenthesis
- Negative Sign
*, /, % Multiplication, Division and Remainder
+, - Addition and Subtraction

©Saif Bashar 2019


CHAPTER 02 Saif.io

If we rewrite the previous code as follows:

int a= (2 + 3) * 4;

The code will produce 20, the addition come first because of the
parenthesis that have the higher precedence then the multiplication
5*4.

Note that if we have an expression with operators with the same


precedence the compiler will take the operation from left to right,
check out the following code:

int a= 2 + 3 – 4 + 1;

The code will produce 2, while all the operators of the same
precedence we work form left to right, so the first operation is 2+3
then 5-4 then 1+1.

If we have nested parenthesis, the precedence always goes to the


most inner parenthesis.

The following code will produce 9, 6, 4 can you figure out why?

int a=5, b=2, c=3, d1, d2, d3;


d1 = a + b * c - 4 / 2;
d2 = a + (b * c - 4) / 2;
d3 = a + (b * (c - 4)) / 2;

Video lecture: Arithmetic Operators Precedencies


https://youtu.be/uAglKFT9lAY

The arithmetic operators and the law of precedence are very critical
in solving mathematical equations, many computer programs
depend on mathematical equations, so we have to master the way
we write a mathematical equation correctly.

©Saif Bashar 2019


CHAPTER 02 Saif.io

As a good example I will take the quadratic equation that we all


know and try to convert it correctly into a programming statement
that gives correct results.

The quadratic equation that have two solutions (roots):

2
-b ± √b - 4ac
x=
2a
For the two solutions of the equation we will have to write two
equations, one for each root:

2 2
-b + √b - 4ac -b - √b - 4ac
x1= x2=
2a 2a

We can see a bunch of operators that we discussed before like the


negative sign, addition, subtraction, multiplication and division. But
we have something new which is the square root and the exponent.
There are many functions that perform the most common
mathematical operations stored in a special library called math.h so
we can include this file and use its built-in functions in our programs.

Math Functions

We have to write #include<math.h> to use these functions

sqrt(x), pow(x,y), exp(x), log(x), log10(x), fabs(x),


sin(x), cos(x), tan(x), sinh(), cosh(), tanh(), floor(),
ceil()

Try to use these functions in your programs and see what they do as I
will use two of them in the quadratic equation example.

©Saif Bashar 2019


CHAPTER 02 Saif.io

A simple algorithm to solve a quadratic equation:

1- Declare the required variables


2- Read the values of a, b, c
3- Calculate the first root x1
4- Calculate the second root x2
5- Print out the results

Converting this algorithm into a working program:

Program 2.4
1 // solving quadratic equation version 1
2 #include<iostream>
3 #include<math.h>
4 using namespace std;
5 main () {
6 int a, b, c;
7 float x1, x2;
8 cout <<"Enter the equation coefficients: ";
9 cin>>a>>b>>c;
10 x1 = -b + sqrt(b*b-4*a*c) / 2*a;
11 x2 = -b - sqrt(b*b-4*a*c) / 2*a;
12 cout<<"The roots are: "<<x1<<" and "<<x2;
13 }

If you wrote a program like Program 2.4 to solve the quadratic


equation you might think that your answer is right but it’s wrong. The
program above works just fine but it does not give the right results,
remember that programming is not just about writing programs,
programming is about writing correct programs that gives corrects
answers.

If we take a simple quadratic equation where a=1, b=6, c=8 like this
one:

x2 +6x+8=0

©Saif Bashar 2019


CHAPTER 02 Saif.io

We can solve it by factoring (x+2) (x+4) =0 so x is either -2 or -4, but


when you apply these values to the program above we will find
different not correct results -5 and -7, so what is the problem in our
program?

The problem is that we didn’t apply the precedence rule to our


equations so the order of operations is not right and it gives wrong
results, in order to ensure correct results, we need to provide
parenthesis to correct the order of operations, this equation:

x1 = -b + sqrt(b*b-4*a*c) / 2*a;

should be rewritten like this


x1 = (-b + sqrt(b*b-4*a*c)) / (2*a);

Program 2.5
1 // solving quadratic equation version 2
2 #include<iostream>
3 #include<math.h>
4 using namespace std;
5 main () {
6 int a,b,c;
7 float x1, x2;
8 cout <<"Enter the equation coefficients: ";
9 cin>>a>>b>>c;
10 x1 = (-b + sqrt(b*b-4*a*c)) / (2*a);
11 x2 = (-b - sqrt(b*b-4*a*c)) / (2*a);
12 cout<<"The roots are: "<<x1<<" and "<<x2;
13 }

Test the program with a=1, b=6, c=8 and see if it gives you the
correct results.

Video lecture: Writing Long Equations Correctly


https://youtu.be/J6IXZxbihOA

©Saif Bashar 2019


CHAPTER 02 Saif.io

An important note I like to tell you before you try to solve the
exercises at the end of the chapter, the note is about the built-in
trigonometric functions, these functions takes an input the angle in
radian not in degrees so for example if you want to calculate
sin(30) you must convert the angle 30 from degrees to radians by
multiplying 30 by 3.14/180, so any angle to be converted from
degrees to radians should be multiplied by this ratio 3.14/180 to get
the correct results.

cout<<sin(30*3.14/180); // for sin(30)


cout<<cos(180*3.14/180); // for cos(180)

©Saif Bashar 2019


CHAPTER 02 Saif.io

Exercises 2
Q1: Find the value if A where A = (5+2*3+((3-2) *7) + -9) / 2

Video lecture: Solution for Q1 - Exercises 2


https://youtu.be/7sjlNN6VxxM

Q2: Write C++ program to read x and compute sin(x), cos(x) and
tan(x)

Video lecture: Solution for Q2 - Exercises 2


https://youtu.be/eMjIsSAlb2o

Q3: Write C++ program to find the area of a circle


Video lecture: Solution for Q3 - Exercises 2
https://youtu.be/X_oDhS99asE

Q4: Write a program to read a set of five real numbers and find the
summation and average of them?
Video lecture: Solution for Q4 - Exercises 2
https://youtu.be/7IRD2tzlYt4

Q5: Write a program for the following equations and make sure it
gives you the correct answers

√Sin(x) x √2Sin(𝑥 3)
y= + y= + 𝑒2
x4 5 x5

Video lecture: Solution for Q5 - Exercises 2


https://youtu.be/eMhD0Nl0bS8

©Saif Bashar 2019


CHAPTER 02 Saif.io

Q6: Write a program to declare enumerated data type and display


the difference between months
Video lecture: Solution for Q6 - Exercises 2
https://youtu.be/V4J2T7oKNpU

Q7: Write a program to declare enumerated data type and display


the number of each season
Video lecture: Solution for Q7 - Exercises 2
https://youtu.be/VFE3xv45NjE

©Saif Bashar 2019


Chapter 03
Logical Decisions
3.1 Introduction
3.2 The Conditional if-else Statement
3.3 Comparison Operators
3.4 Logical Operators
3.5 Nesting Conditions
3.6 The Conditional switch Statement
3.7 Bitwise Operators
Exercises 3

s a i f . i o
CHAPTER 03 Saif.io

3.1 Introduction
The programs we wrote in the previous chapters have a serial
way of execution, I mean the lines of code took a top down path
without skipping any line. Here in this chapter we will make the
program skip some lines of code and execute other lines of code
based on a specific condition or conditions. We will make the
programs look smarter and take some logical decisions, we will not
only make a program go from top to down but rather decide to go
left or right.

We can change the flow of a program by using the conditional


statements that are very common control structure that you can find
in any programming language. In C/C++ there are two conditional
statements the if-else statement and the switch statement that
we will discuss them in this chapter.

The basic concept in the conditional statements or sometimes called


branching (rhombus shape in flowcharts), is that there is a condition
that is evaluated first and if the outcome of this evaluation was true
then a statement or a group of statements are executed, if the
outcome of the evaluation is false then another statement or group
of statements are executed.

3.2 The Conditional if-else Statement


The syntax of if-else statement in C/C++ is:

if-else Statement Syntax

if (expression)
statement1;
else
statement2;

©Saif Bashar 2019


CHAPTER 03 Saif.io

The syntax above evaluates the expression first if the outcome was
true then statement1 is executed and statement2 is skipped. If the
evaluation outcome was false then statement2 is executed and
statement1 is skipped.

Note that we can write if statement without else, but we cannot


write else without if statement. We can use the single if statement
when we don’t want anything to be executed when the condition is
false.

if Statement Syntax

if (expression)
statement1;

If we wanted more than one statement to be executed we have to


group the statements using curly braces and you can add as many
statements you want, like the following syntax:

if-else Statement Syntax (multiple statements)

if (expression)
{statement1;
statement2;}
else
{statement3;
statement4;
statement5;}

If you forgot to include the curly braces in multiple statements, then


the if-else will take only the first statement for its execution. In the
syntax above if you didn’t write the curly braces then statement1
will be considered a statement for the if statement, and

©Saif Bashar 2019


CHAPTER 03 Saif.io

statement3 for the else. While statement2, statement4, and


statement5 will be considered outside the if-else construct.

3.3 Comparison Operators


The expression that need to be evaluated needs special types
of operators to enable us create conditions. We discussed the
arithmetic operators before, here we will discuss another type of
operators, firstly I’ll start with comparison operators and as the name
imply that the comparison operators used if we want to compare
two values, and they are six operators listed in the table below:

Comparison Operators
Operator The Comparison Example
>= Larger than or equal? if (a >= b)
<= Less than or equal? if (a <= b)
> Larger than? if (a > b)
< Less than? if (a < b)
== Equals? if (a == b)
!= Not equals? if (a != b)

A Common Mistake == is not =

Be careful not to confuse the equality operator ==


with the assignment operator =

The equality operator compares two values if they


are the same it returns true if not it returns false

The assignment operator takes the value at the


right-hand side and assign it to the variable at the
left-hand side and it always be true unless we assign
zero to the variable.

A simple program to illustrate the use of if-else statement, the


program checks if we are old enough to have a driver license, an
algorithm to the program could be like this:

©Saif Bashar 2019


CHAPTER 03 Saif.io

- Declare a variable to store the user’s age


- Read the user’s age
- Check if the age is larger or equal 18 then print a suitable
message
- Check if the age is less than 18 then print a suitable message

The program can be something like this:

Program 3.1
1 // if-else statement
2 #include<iostream>
3 using namespace std;
4 main () {
5 int age;
6 cout<<"Hi, How Old Are You? ";
7 cin>>age;
8 if (age >= 18)
9 cout<<"You can have a driver’s license:";
10 else
11 cout<<"You still young to have a license";
12 }

Note that the program above also can be written like this:

Program 3.2
1 // multiple if statements
2 #include<iostream>
3 using namespace std;
4 main () {
5 int age;
6 cout<<"Hi, How Old Are You? ";
7 cin>>age;
8 if (age >= 18)
9 cout<<"You can have a driver’s license:";
10 if (age < 18)
11 cout<<"You still young to have a license";
12 }

©Saif Bashar 2019


CHAPTER 03 Saif.io

Program 3.1 is faster since it checks only once, while Program 3.2
perform two checks, we always want to solve problems with the least
operations to write fast and efficient programs. But in some cases,
we have to use multiple if statements without else when we have
non-mutual exclusive conditions.

3.4 Logical Operators


Sometimes we need to combine more than one condition in an
expression, we use the logical operators to do that, the three logical
operators are listed in the following table:

Logical Operators
Operator Operation Example
! NOT if (!a)
&& AND if (a>=b && b!=5)
|| OR if (a<=b || b==9)

The logical operators follow the rules of Boolean logic according to


the following truth tables:

A B A && B A B A || B
false false false false false false A !A
false true false false true true false true
true false false true false true true false
true true true true true true

Note that the logical operators also have a law of precedence the
logical NOT with the highest precedence then the logical AND then
the logical OR.

Also remember that C++ consider all numbers true except zero is
always false.

Watch the following video for more explanation and examples on


the if-else statement.

Video lecture: Conditional if-else Statement


https://youtu.be/JLbbdUY_pwA

©Saif Bashar 2019


CHAPTER 03 Saif.io

3.5 Nesting Conditions


Nesting is a very common term in programming, it simply means
making a statement inside another statement, when we want to nest
more than one statement we use the curly braces as we said before.

Nesting is not exclusive to the conditional statements we can use it in


any control structure that we will study later, but in conditional
statements we can imagine nesting of if statement inside another if
statement when we want to make a second check when the first
one is passed, we also could do a third check inside the second and
so on.

For example, if we want to test a number if it is positive or negative


then check it again if it is even or odd, an algorithm could be like
this:

1- Define an integer as number


2- Read number
3- Check if number >0
a. Check number % 2 == 0
b. Print number is positive and even
c. Else print number is positive and odd
4- Else if number <0
a. Check number % 2 == 0
b. Print number is negative and even
c. Else print number is negative and odd
5- Else print number is zero

The algorithm can be converted to Program 3.3 below, notice the


multiple if-else statements and make sure to write your programs
with proper indenting.

Indenting will make your code clear in nesting to see what statement
belong to what peace of code, without indenting programs will
become harder to understand.

©Saif Bashar 2019


CHAPTER 03 Saif.io

Program 3.3
1 // Nesting if statements
2 #include<iostream>
3 using namespace std;
4 main () {
5 int number;
6 cout<<"Give me a number: ";
7 cin>>number;
8 if (number > 0)
9 if (number % 2 == 0)
10 cout<<"number is positive and even";
11 else
12 cout<<"number is positive and odd";
13 else if (number < 0)
14 if (number % 2 == 0)
15 cout<<"number is negative and even";
16 else
17 cout<<"number is negative and odd";
18 else
19 cout<<"number is zero";
20 }

There is an operator that make the if-else statement more


condense, it’s called the ternary operator the syntax is as follows:

Ternary Operator Syntax

variable = expression ? value1 : value2;

The expression is evaluated first, if the expression returned true then


value1 is assigned to the variable, if the expression returned false
then value2 is assigned to the variable. It is considered a shortcut to
the following syntax:

©Saif Bashar 2019


CHAPTER 03 Saif.io

if-else Syntax
if (expression)
variable = value1;
else
variable = value2;

The program to test even from odd numbers could be rewritten like
this:

Program 3.4
1 // Ternary operator
2 #include<iostream>
3 using namespace std;
4 main () {
5 int number;
6 cout<<"Give me a number: ";
7 cin>>number;
8 (number % 2)? cout<<"Odd": cout<<"Even";
9 }

Watch the following video for more explanation and examples on


nesting if-else statements.

Video lecture: Nesting if-else Statements


https://youtu.be/qKJS5eFX0kQ

©Saif Bashar 2019


CHAPTER 03 Saif.io

3.6 The Conditional switch statement


C/C++ languages provide another keyword for logical
decisions, the keyword is switch, the switch statement can be used
to solve programs that have many conditions (cases), so instead of
using multiple if-else statements we can use the switch
statement, some programmers prefer to use the multiple if-else
statements other programmers prefer to use the condense structure
of switch statement, the syntax of switch statement look like this:

switch Statement Syntax

switch (expression){
case value1 : statement1; statement2; break;
case value2 : statement3; break;
case value3 : statement4; statement5; break;
case value4 : statement6; statement7; break;
default: statement8;
} //end of switch block

The switch statement as the name imply it simply switch a value to


match a case, then execute every statement in that case. The
break keyword means stop the execution and step out of the switch
block.

If no case matches the value then the default case executes its
statements, you don’t have to use the break command in the
default case because there is no other case below it. If you forgot to
write break the execution will fall through the next case until it
reaches a break command.

I will show you an example and I will solve it using multiple if-else
statements then I will solve the same example using switch
statement for you to notice the differences.

©Saif Bashar 2019


CHAPTER 03 Saif.io

For example, if we want to write a program that reads a student


grade (A, B, C, D, E or F) then print a suitable message, using multiple
if-else statements it will be something like the following program.

Program 3.5
1 // multiple if-else statements
2 #include<iostream>
3 using namespace std;
4 main () {
5 char grade;
6 cout<<"What’s your grade? ";
7 cin>>grade;
8 if (grade == ‘A’)
9 cout<<"Excellent";
10 else if (grade == ‘B’)
11 cout<<"Very Good";
12 else if (grade == ‘C’)
13 cout<<"Good";
14 else if (grade == ‘D’)
15 cout<<"Medium";
16 else if (grade == ‘E’)
17 cout<<"Accepted";
18 else if (grade == ‘F’)
19 cout<<"Work Harder";
20 else
21 cout<<"Enter A, B, C, D, E or F";
22 }

The same example can be solved using the switch statement, the
following Program 3.6 have less lines of code and produce the same
results as Program 3.5, the switch statement replaces the multiple
if-else statements with more condense code segment.

©Saif Bashar 2019


CHAPTER 03 Saif.io

Program 3.6
1 // multiple if-else statements
2 #include<iostream>
3 using namespace std;
4 main () {
5 char grade;
6 cout<<"What’s your grade? ";
7 cin>>grade;
8 switch (grade) {
9 case ‘A’: cout<<"Excellent"; break;
10 case ‘B’: cout<<"Very Good"; break;
11 case ‘C’: cout<<"Good"; break;
12 case ‘D’: cout<<"Medium"; break;
13 case ‘E’: cout<<"Accepted"; break;
14 case ‘F’: cout<<"Work Harder"; break;
15 default: cout<<"Enter A, B, C, D, E or F";
16 } //end of switch
17 }

©Saif Bashar 2019


CHAPTER 03 Saif.io

Note that in the previous releases of C++ language the switch


statement was only capable to solve multiple if-else statements
with a specific value you can’t use it for a range of values. But in
newer releases an operator was added to make the switch
statement support ranges of values. The operator is the three dots
operator ... so if we want to solve Program 3.2 with switch
statement it would be something like this:

Program 3.7
1 // switch statement with ranges
2 #include<iostream>
3 using namespace std;
4 main () {
5 int age;
6 cout<<"Hi, How Old Are You? ";
7 cin>>age;
8 switch(age){
9 case 18 ... 100:
10 cout<<"You can have a driver’s license:";
11 break;
12 case 0 ... 17:
13 cout<<"You still young to have a license";
14 break;
15 default:
16 cout<<"Please enter a valid Age";
17 }
18 }

The first case will include all the values from 18 to 100, the second
case will take the values from 0 to 17, the default case will catch any
number above 100 and below zero.

©Saif Bashar 2019


CHAPTER 03 Saif.io

3.7 Bitwise Operators


The bitwise operators as the name implies are a group of
operators that works at the bit level, which means that these
operators will convert the two numbers into its binary representation
then perform a logical operation on it bit by bit. The logical
operations are the same as the truth tables listed before adding the
XOR table below:

A B A XOR B
false false False
false true True
true false True
true true false

The six bitwise operators are listed in the table below:

Bitwise Operators
Operator Operation Example
x = 12 & 10;
& Bitwise AND
1100 AND 1010 = 1000 = 8
x = 12 | 10;
| Bitwise OR
1100 OR 1010 = 1110 = 14
x = ~12;
~ Bitwise NOT
NOT(1100) = ?
x = 12 ^ 10;
^ Bitwise XOR
1100 OR 1010 = 0110 = 6
x = 3>>1;
>> Bitwise Right Sift
output = 1
x = 3<<1;
<< Bitwise Left Shift
output = 6

Note that the shifting operations use the same extraction and
insertion operators used with cin and cout, this is very common in
C/C++ languages to use an operator for multiple purposes.

The left shift operation 3>>1 means to shift the bits of the number
three to the right by one place. So, first the number three is
converted to binary 11 then shifting the bits to the right by one place
mean add a zero from the left, the number will become 01.

©Saif Bashar 2019


CHAPTER 03 Saif.io

For more illustration

Shift Operations
x=3; // 011
x=x>>1; // 001 which equals to 1

x=3; // 011
x=x<<1; // 0110 which equals to 6

x=260; // 100000100
x=x>>5; // 000001000 which equals to 8

x=260; // 100000100
x=x<<5; // 10000010000000 which equals to 8320

Remember that the total number of places to represent an integer


are 32 because the size of integer is 4 bytes as we calculated that in
chapter 2, if the shifting operation require more places than the
number can handle, the number will round on itself and produce
wrong results.

We can use the shortcuts like we did with the arithmetic operators
like the following table:

Bitwise Operation Shortcut


a=a&b; a&=b;
a=a|b; a|=b;
a=a^b; a^=b;
a=a>>b; a>>=b;
a=a<<b; a<<=b;

Another important note that I should tell you about is that the bitwise
NOT operation negate the whole 32 bits in the case of integers so
when you try to do NOT(1100) the answer in not 0011, because the
NOT operation negate all 32 bits and the correct answer will be

11111111 11111111 11111111 11110011

©Saif Bashar 2019


CHAPTER 03 Saif.io

Which is a negative number in binary and it equals to -13, I’ll explain


to you why -13 in the videos below.

This video explains the bitwise operators, and how to convert from
decimal to binary system.

Video lecture: Bitwise Operators


https://youtu.be/KokPcCYhHCA

Another video you might find it useful, in this video I explain how to
convert to and from the four number systems used in computer
science the decimal, octal, hexadecimal and binary number
systems.

Video lecture: Number Systems


https://youtu.be/cIQ6_Xm4FSU

C/C++ geeks try to challenge each other by mixing various


operators’ types in a single expression to guess what the output will
be, only a programmer with a solid understanding to how different
operators work will find the correct answer, for example what do you
think the output of the following expression will be?

Mixed Operators

cout << ((3|2) && (4&5)) || (1>7);

So, you typed the code and found the output is 1, but can you tell
why 1? Take a pen and a paper and try to solve the expression
above step by step.

©Saif Bashar 2019


CHAPTER 03 Saif.io

Exercises 3
Q1: Write a program that reads two integers then prints “multiple” or
“not multiple” if one number is a multiple of the other
Video lecture: Solution for Q1 - Exercises 3
https://youtu.be/EazM8REHCdw

Q2: Write a program that reads three numbers then find the largest
and smallest number
Video lecture: Solution for Q2 - Exercises 3
https://youtu.be/ErMfudhdMSg

Q3: Write a program that reads an integer number and check if it is


positive or negative, even or odd and write a suitable message in
each case
Video lecture: Solution for Q3 - Exercises 3
https://youtu.be/s4G6EWXgEXY

Q4: Write a program that reads x and prints sin(x) if x>0, square root
of x if x<0 and absolute value of x if x/2 is integer
Video lecture: Solution for Q4 - Exercises 3
https://youtu.be/uE2RusxQ16o

Q5: Write a program that reads five numbers and check if the
numbers are in ascending order or not
Video lecture: Solution for Q5 - Exercises 3
https://youtu.be/gMsuDXaSSJ8

©Saif Bashar 2019


CHAPTER 03 Saif.io

Q6: Write a program that reads a character and check if it is a digit


(0 – 9), a capital letter (A, B, … Z), a small letter (a, b, … z) or a
special character
Video lecture: Solution for Q6 - Exercises 3
https://youtu.be/gVZ0AVNrD8w

Q7: Write a program that reads x and compute the following:

𝑥 2 + 5𝑥 − 20
𝑖𝑓 𝑥 > 0
𝑦= √2𝑥
0 𝑖𝑓 𝑥 = 0
2
{ 𝑥 + 10𝑥 − 10 𝑖𝑓 𝑥 < 0

Video lecture: Solution for Q7 - Exercises 3


https://youtu.be/buGPqVpxFPU

Q8: Write a program that reads a student’s score and print his/her
estimate grade

90-100 Excellent
80-89 Very Good
70-79 Good
60-69 Medium
50-59 Accepted
0-49 Fail

Video lecture: Solution for Q8 - Exercises 3


https://youtu.be/GxXecCUeJ9Q

Q9: Write a program that reads an integer and print its equivalent
string (take numbers from 0 to 9)
Video lecture: Solution for Q9 - Exercises 3
https://youtu.be/VXWDeIZzWik

©Saif Bashar 2019


CHAPTER 03 Saif.io

Q10: Write a program that reads an integer and print its equivalent
string
Video lecture: Solution for Q10 - Exercises 3
https://youtu.be/VXWDeIZzWik

Q11: Write a program that reads an integer from 1 to 12 and print out
the corresponding month of the year
Video lecture: Solution for Q11 - Exercises 3
https://youtu.be/YmYXAAlbex4

Q12: Write a program that reads two integers, and read the
arithmetic operation to perform on these numbers
Video lecture: Solution for Q12 - Exercises 3
https://youtu.be/w4AEFK9iQ5Y

Q13: Write a program to represent a simple nested switch statement


Video lecture: Solution for Q13 - Exercises 3
https://youtu.be/m8Jd5o7v-kU

Q14: Solve the following Expressions (find the value of m with steps):
x = 11
m = (6>1) | (6^16) & x++
-------------------------------------------------------

m = ((5>4) || (6<3) && (12 & 9)) ^ 7


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

x = 10
m = (6<1) | (20^16) & x++ + 1

Video lecture: Solution for Q14 - Exercises 3


https://youtu.be/ellPkbH2DDk

©Saif Bashar 2019


CHAPTER 03 Saif.io

Q15: Find the value of B for the following expression (with steps):
i=5
j=9
B = !((i>0) && (i>=j))

Video lecture: Solution for Q15 - Exercises 3


https://youtu.be/J5gvDV4l12A

Q16: Given that A and B are real numbers with values 1.5 and 2.5
respectively, and C is an integer number with value 3, evaluate the
following expression
NOT((A<0) AND (B/C<=0)

Video lecture: Solution for Q16 - Exercises 3


https://youtu.be/ynMTYJijOxQ

©Saif Bashar 2019


Chapter 04
Loops
4.1 Introduction
4.2 Iterative for Statement
4.3 Iterative while Statement
4.4 Iterative do-while Statement
4.5 break & continue Keywords
4.6 Nested Loops
Exercises 4

s a i f . i o
CHAPTER 04 Saif.io

4.1 Introduction
Another fundamental control structure provided in all
programming languages is the loops or iterations, loops provide a
mechanism to repeat instructions for number of times. For example, if
you want to print the numbers from 1 to 100 you can do that using a
single loop statement rather than repeating the cout 100 times.

C/C++ languages provide three types of loops: the while statement,


the do-while statement and the for statement, but before we use
any loop statement we have to think about three things:

- Starting point for the loop’s counter


- A stop condition if satisfied the loop will end
- The steps to reach from the starting point to the stop condition

The stop condition is very critical because if you didn’t write it


correctly your program may enter an infinite loop and eventually
crash, also if you forgot to increase or decrease the loop’s counter
you will enter an infinite loop, this is very common error to fall into
when you start working with loops.

The steps for the counter to reach the stop condition could be by
incrementing the counter by one ++i or decrementing the counter
by one --i or incrementing by two i+=2, decrementing by two i-=2
or any number depending on the number of steps you need and
how much you want to increment or decrement the loop’s counter.

©Saif Bashar 2019


CHAPTER 04 Saif.io

4.2 Iterative for Statement


The for statement usually used when we already know how
many loops we want, the syntax of for statement:

for Statement Syntax

for (initialization; stopCondition; step){


statement1;
statement2;
statement3; } //end of for block

Printing numbers from 1 to 100, the code will be something like this:
for (int i=1; i<=100; i++){
cout<<"Loop: "<<i<<endl; }

The for statement will work like this:

- The initialization part executed first and only once, in the


example declare a variable that will work as a counter for the
loop
- The stop condition is checked if it is true the block of for
statement will be executed its, otherwise exit the for loop.
- If the stop condition’s expression evaluated to true and the
statements executed, the counter incremented by one.
- The stop condition will be checked again, and so on until the
counter reaches 101 which makes the condition false and exit
the loop

Note that the curly braces are not mandatory in our example
because the for statement has only one cout statement, but if we
require more than one statement for the loop to be executed then
we must put curly braces.

©Saif Bashar 2019


CHAPTER 04 Saif.io

We can also decrement the counter like the following code:


for (int i=100; i>=1; i--){
cout<<"Loop: "<<i<<endl; }

The examples above show you the standard syntax of the for loop,
but we can write it like this also
for (int i=1; i<=100; ){
cout<<"Loop: "<<i<<endl;
i++;
}

We can also write it like this:


int i=1;
for ( ; i<=100; ){
cout<<"Loop: "<<i<<endl;
i++;
}

And like this:


int i=1;
for ( ; ; ){
cout<<"Loop: "<<i<<endl;
if(i>=100)
break;
i++;
}

All of them produce the same result, but the first example is the most
common way of writing the for loop since it’s the way that require
less lines of code. Note that you cannot delete the semi colons inside
the for loop.

©Saif Bashar 2019


CHAPTER 04 Saif.io

4.3 Iterative while Statement


The while loop is usually used when we don’t know the number
of iterations we need, like for example if the total number of
iterations depends on a user input.

The while loop syntax is:

while Statement Syntax

initialization;
while (stopCondition){
statement1;
statement2;
statement3;
step; } //end of while block

The previous examples could be written in while loop:

int i=1;
while (i<=100){
cout<<"Loop: "<<i<<endl;
i++; }

int i=100;
while (i>=1){
cout<<"Loop: "<<i<<endl;
i--; }

The initialization of the counter is written before the while loop, the
while loop will check the condition first, if it is true then it executes
the statements in its body, the last statement will be the step to
increase or decrease the counter.

The while loop will terminate when the condition become false.

©Saif Bashar 2019


CHAPTER 04 Saif.io

4.4 Iterative do-while Statement


The do-while loop is like the while loop except in checking
the condition, the do-while loop checks the condition in the last
step, this means if the condition is false from the beginning the do-
while loop executes for one time, the do-while syntax is:

do-while Statement Syntax

initialization;
do {
statement1;
statement2;
statement3;
step; }
while (stopCondition);

As the syntax shows that the conditions come at the end, the
previous examples in do-while will be like:

int i=1;
do{
cout<<"Loop: "<<i<<endl;
i++; }

while (i<=100);

int i=100;
do{
cout<<"Loop: "<<i<<endl;
i--; }

while (i>=1);

but you will see that 101 and 0 will be printed here, can you guess
why?

©Saif Bashar 2019


CHAPTER 04 Saif.io

4.5 break & continue Keywords


You can use the break keyword that we used in switch
statement before, you can use it with loops to stop the loop
execution and step out the loop’s block according to some
condition, for example the following code will print only the first 49
numbers not the whole 100

for (int i=1; i<=100; i++){


if(i==50)
break;
cout<<i<<endl; }

The break keyword can be used with any type of loops.

Also, you can skip some iterations inside the loop using the continue
keyword according to some condition, for example the following
code will print out all numbers from 1 to 100 except the number 50
for (int i=1; i<=100; i++){
if(i==50)
countinue;
cout<<i<<endl; }

Video lecture: Loops


https://youtu.be/hAldLNt-GcE

©Saif Bashar 2019


CHAPTER 04 Saif.io

We can use the construct of loops to solve many problems that


require repetitive operations, let’s take a couple of examples, the first
one will demonstrate how the power function works, I mean raising a
number to an exponent. The second example will solve the factorial
of a number.

When we think about the operation of raising a number to a power,


it is really an operation of repetitive multiplication. The product of the
number by itself as many as the exponent, so 2 3 mean 2*2*2, and 210
is 2*2*2*2*2*2*2*2*2*2 so we can use loops to do that, making the
exponent as our counter decrementing by one, the loop body can
accumulate the product of the number, the code can be as the
following program:

Program 4.1
1 // calculating power
2 #include<iostream>
3 using namespace std;
4 main () {
5 int number, exponent;
6 long result = 1;
7
8 cout<<"Give me a Number: ";
9 cin>>number;
10
11 cout<<"Give me an Exponent: ";
12 cin>>exponent;
13
14 for (int i=exponent; i>=1; --i){
15 result *= number;
16 }
17
18 cout<<"The Result: "<<result;
19 }

©Saif Bashar 2019


CHAPTER 04 Saif.io

Another famous example is the factorial of a number which is the


product of the numbers from 1 to the number itself. We also can use
loops to multiply all the numbers and decrement or increment the
counter, for example the factorial of 5 is 5*4*3*2*1 or 1*2*3*4*5, I will
try to solve it using while loop, the code can be like the following
program:

Program 4.2
1 // calculating factorial
2 #include<iostream>
3 using namespace std;
4 main () {
5 int number;
6 long result = 1;
7
8 cout<<"Give me a Number: ";
9 cin>>number;
10
11 for(int i=number; i>=1; --i){
12 result *= i;
13 }
14
15 cout<<"The Result: "<<result;
16 }

©Saif Bashar 2019


CHAPTER 04 Saif.io

4.6 Nested Loops


Sometimes we need a loop to be inside another loop, we will
make use of this in multi-dimensional arrays on the upcoming
chapters. To demonstrate the nested loops, for example if we have a
two-dimensional figure with rows and columns we can use two loops
one for the rows and the other one for the columns we can use
nested loops to draw the following figure:

*****
*****
*****
*****

We can use two loops, one loop is for rows that start with 1 and end
with 4, the second loop is for columns that start with 1 and ends with
5, the following program gives the previous result:

Program 4.3
1 // drawing a rectangle
2 #include<iostream>
3 using namespace std;
4 main () {
5 int rows = 4;
6 int columns = 5;
7
8 for (int i=1; i<=rows; ++i){
9 for (int j=1; j<=columns; ++j) {
10 cout<<"*"; } //end of columns loop
11
12 cout<<endl;
13 } //end of rows loop
14 }

©Saif Bashar 2019


CHAPTER 04 Saif.io

It’s a good practice to always use curly braces with nested loops to
recognize easily what statements belong to which loop.

Note that always give every loop its own counter in the example
above we used i for the rows loop and j for the columns loop, also
always write your code in proper code indenting to make the code
readable.

Another example trying to draw the following figure:

12345
1234
123
12
1

The figure above has 5 rows, let’s name the counter for rows i that
begin from 5 and decremented to 1, but what about the columns
we can clearly see that the columns in each row are less by one, so
in the first row I need five columns, in the second row I need four
columns, in the third row I need three columns and so forth.

In these types of figures, we have to think about a relation between


the rows and columns, so I suggested to start the rows counter with 5,
and I need columns form 1 to the values of i, so the number of
columns depends on the counter of rows on each iteration in this
example.

Note that you can always come up with a different approach


solving any program in this book, maybe yours will be better than
mine.

©Saif Bashar 2019


CHAPTER 04 Saif.io

The code of the program to draw the previous figure can be


something like this:

Program 4.4
1 // drawing a triangle
2 #include<iostream>
3 using namespace std;
4 main () {
5
6 for(int i=5; i>=1; --i){
7 for(int j=1; j<=i; ++j) {
8 cout<<j; } //end of columns loop
9
10 cout<<endl;
11 } //end of rows loop
12 }

More examples can be found in this video

Video lecture: Nested Loops


https://youtu.be/B5U48is5Ws0

An important tool that is very useful for a programmer especially with


loops, the tool is called trace or debug, a trace means tracking your
program and watching step by step what happen with the variables,
what values they take during the program execution.

Tracing your program helps you find bugs in your code, and spot the
buggy piece of code for you to fix. The CodeBlocks IDE that we are
working with provide this tool, I have a video for you to show you
how to use this helpful tool:

Video lecture: Tracing Tool


https://youtu.be/IMqNTXT-Cys

©Saif Bashar 2019


CHAPTER 04 Saif.io

Exercises 4
Q1: Write a program that displays the first 100 odd number using
while loop

Video lecture: Solution for Q1 - Exercises 4


https://youtu.be/rqNkSgvgHuI

Q2: Write a program to find the summation of the odd numbers


between 0 and 100 using while loop

Video lecture: Solution for Q2 - Exercises 4


https://youtu.be/bpuSePx0dmk

Q3: Write a program to read a student’s information then calculate


his/her average, then print “Pass” if he/she passes or “Fail” otherwise
Video lecture: Solution for Q3 - Exercises 4
https://youtu.be/xSx3ksTX0Ik

Q4: Write a program to test a number is it a prime or not prime


Video lecture: Solution for Q4 - Exercises 4
https://youtu.be/y--9gqJ2jDE

Q5: Write a program to generate Fibonacci sequence using loops


Video lecture: Solution for Q5 - Exercises 4
https://youtu.be/lxs8mPi-CYY

Q6: Write a program to calculate the GCD between two numbers


Video lecture: Solution for Q6 - Exercises 4
https://youtu.be/xSNeZTs3iK0

©Saif Bashar 2019


CHAPTER 04 Saif.io

Q7: Write a program to solve the following mathematical series:

𝑦 = 1 − 𝑥2 + 𝑥3 + 𝑥4 … … 𝑥𝑛
Video lecture: Solution for Q7 - Exercises 4
https://youtu.be/jH-XVRTOfSQ

Q8: Write a program to solve the following mathematical series:


1 1 1 1
𝑒=1+ + + ……
1! 2! 3! 𝑛!
Video lecture: Solution for Q8 - Exercises 4
https://youtu.be/Qwfj7c_ZPMI

Q9: Write a program to solve the following mathematical series:

𝑥 𝑥2 𝑥3 𝑥𝑛
𝑒 =1+ + + ……
1! 2! 3! 𝑛!
Video lecture: Solution for Q9 - Exercises 4
https://youtu.be/_vTWN2iXUxY

Q10: Write a program to solve the following mathematical series:

𝑠𝑢𝑚1 = 1 + 22 + 42 … … 𝑛2

𝑠𝑢𝑚2 = 1 − 3𝑥 + 5𝑥 − … … 𝑛𝑥
1 2 3 𝑛
𝑠𝑢𝑚3 = 1 + + + ……
1! 2! 3! 𝑛!

Video lecture: Solution for Q10 - Exercises 4


https://youtu.be/sjAV1eI0TzM

Q11: Write a program to reverse an integer number


Video lecture: Solution for Q11 - Exercises 4
https://youtu.be/n21WsFPvESA

©Saif Bashar 2019


CHAPTER 04 Saif.io

Q12: What is the output of the following code segment:


int i=12;
do{
cout<<i<<endl;
i--; }

while (i>0);

Video lecture: Solution for Q12 - Exercises 4


https://youtu.be/-VbUQ8h7qIk

Q13: What is the output of the following code segment:


int count=1;
do{
cout<<(count % 2 ? "****": "+++++")<<endl;
++count; }

while (count<=10);

Video lecture: Solution for Q13 - Exercises 4


https://youtu.be/iTyyrxs_VXY

Q14: What is the output of the following code segment:


for(;;)

{ cout<<"Enter your number";


cin>>x;
if(x % 2 == 0)
continue;

if(x % 3 == 0)
break;

cout<<"bottom of loop"<<endl;
}

Video lecture: Solution for Q14 - Exercises 4


https://youtu.be/CTu4oeI7IpQ

©Saif Bashar 2019


CHAPTER 04 Saif.io

Q15: What is the output of the following code segment:


for(int count=7; count<=16; count++)

switch (count%10){

case 0: cout<<","; break;


case 1: cout<<"often"; break;
case 2:
case 8: cout<<"is"; break;
case 3: cout<<"not"; break;
case 4:
case 9: cout<<"done"; break;
case 5: cout<<"well"; break;
case 6: cout<<"."; break;
case 7: cout<<"what"; break;
default: cout<<"bad number";

cout<<endl<<"goodbye";

Video lecture: Solution for Q15- Exercises 4


https://youtu.be/PDNBX3fYkx8

Q16: What is the output of the following code segment:


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

{ if(i % 2 == 0)
cout<<i+1<<endl;
else if(i % 3 == 0)
continue;
else if(i % 5 == 0)
break;

cout<<"end of program\n";
}
cout<<"end…";

Video lecture: Solution for Q16 - Exercises 4


https://youtu.be/erlLearZ4MA

©Saif Bashar 2019


CHAPTER 04 Saif.io

Q17: Write a program to read seven marks for a student then print
“pass” if the student passes, otherwise print “fail”
Video lecture: Solution for Q17 - Exercises 4
https://youtu.be/Guw6GVdkiWI

Q18: Write a program to read 10 marks, suppose the student pass if


all marks greater than or equal to 50 and the average is greater than
or equal to 50. If the student fails in some lessons then print the
number of these lessons. If the student fails in the average then print
“fail in average”
Video lecture: Solution for Q18 - Exercises 4
https://youtu.be/_xPEnY-2HQg

Q19: Write a program to add the numbers between 1 and 100 and
find the average
Video lecture: Solution for Q19 - Exercises 4
https://youtu.be/-DBPM1RDQz4

Q20: Write a program that utilize the do-while loop and escape
sequence ‘\t’ to print the following table:

N 10*N 100*N 1000*N


1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000

Video lecture: Solution for Q20 - Exercises 4


https://youtu.be/PmWKyQi-ubg

©Saif Bashar 2019


CHAPTER 04 Saif.io

Q21: Print the following figure (using loops):

1
21
321
4321
54321

Video lecture: Solution for Q21 - Exercises 4


https://youtu.be/4g7b3cR5JFo

Q22: Print the following figure (using loops):

++++++++++
+++++++++
++++++++
+++++++
++++++
++++
+++
++
+

Video lecture: Solution for Q22 - Exercises 4


https://youtu.be/Ll_6Hko83_Y

Q23: Print the following figure (using loops):

1
333
55555
7777777
999999999
7777777
55555
333
1

Video lecture: Solution for Q23 - Exercises 4


https://youtu.be/CHu8IPtHVP0

©Saif Bashar 2019


Chapter 05
Functions
5.1 Introduction
5.2 Function Implementation
5.3 Function Calling
5.4 Function Declaration
5.5 Functions’ Types
5.6 Passing Parameters
5.7 Function Overloading
5.8 Default Arguments
5.9 Global & Local Variables
5.10 Recursion
Exercises 5

s a i f . i o
CHAPTER 05 Saif.io

5.1 Introduction
Another fundamental concept in all of programming languages is
the concept of a function, we have seen a single function so far in this
book which is the main function, in this chapter we will see how to build our
own functions and how to make them run whenever we want. Functions
give us more organized, readable and efficient programs.

Functions main advantage is to group pieces of code into a module and


run it whenever the program needs, for example if we have a program
that calculate the factorial for the number 5, and we used a loop as we
did before in the previous chapter, now suppose later on the same
program we needed to calculate the factorial for the numbers 6,7,8. We
have to write a loop for each number. So, we have a long program with
four loops all do the same job which is calculating a factorial for a number.

We can use a function that we will build with only one loop, then pass to it
the numbers we want to calculate the factorial for and the function will
return to us the desired output. This will result in a lot shorter, faster program
and easier to fix and develop, the code with functions is more
maintainable.

The concept of functions in programming is similar to the function concept


of mathematics (sort of) in mathematics as we recall functions written in
the following form:
𝑦 = 𝑓(𝑥)

Which means that the function has a name f and it takes an input x and
returns an output that will be stored in the variable y, so for example the
trigonometric sine function if we give it 30 degrees as an angle it will return
to us the trigonometric ratio for this angle which is 0.5

𝑦 = sin(30)
𝑦 = 0.5

©Saif Bashar 2019


CHAPTER 05 Saif.io

5.2 Function Implementation


The syntax of implementing a function in C/C++ require from us to
think of many things:

1- Function’s name: we have to think of a suitable name for our


function, we have to give it an identifier with the same conditions
that we applied on variables, see Chapter 2.

2- Function’s input: what this function should take as an input? How


many parameters or arguments should it receive? note that we
can build a function that do not receive any input as we will see
later.

3- Function’s body: what is the code will be inside the curly braces?
The code that will represent the function’s task. What we want the
function to do for us?

4- Function’s Output Type: what is the output type that the function
will produce, what will it return? Does it return an int, a float, a
string or something else? Note if a function does not return
anything we use the keyword void.

Function Implementation (Definition)

returnType functionName(arguments){
statement1;
statement2;
statement3;
return value;
} //end of function block

©Saif Bashar 2019


CHAPTER 05 Saif.io

5.3 Function Calling


After implementing a function, it will not be executed. Executing
functions happens only when we call them, calling a function happens
when we write its name and give it proper arguments that match its
implementation.

Function Calling

int main(){

int result = functionName(parameters);


return 0;
}

Note that we can call a function from the main function or from any other
user defined function.

As an example, I will try to write the factorial program that we saw in


Chapter 4 – Program 4.2, using functions, the code will be something like
Program 5.1.

You might say that a program with function (Program 5.1) took much more
lines of code that a program without function (Program 4.2), I will tell you
for calculating a single number you are right, but what if you needed to
calculate factorial for more numbers? In this situation writing a function is
the best practice to write code since you don’t have to repeat the
factorial code over and over again.

©Saif Bashar 2019


CHAPTER 05 Saif.io

Program 5.1
1 // calculating factorial using function
2 #include<iostream>
3 using namespace std;
4
5 long fact(int number){
6 long result = 1;
7 for (int i=number; i>1; --i){
8 result *= i;
9 }
10 return result;
11 } //end of fact function
12
13 int main () {
14 int number;
15 long result;
16
17 cout<<"Give me a Number: ";
18 cin>>number;
19
20 result = fact(number);
21 cout<<"The Result: "<<result;
22
23 return 0;
24 } //end of main function

You can now calculate the factorial for as many numbers as you want
with only one function implementation, but you have to call the function
with the number you want to calculate its factorial, something like this:

int main(){

cout<<fact(3)<<endl;
cout<<fact(4)<<endl;
cout<<fact(5)<<endl;
cout<<fact(6)<<endl;
return 0;
}

©Saif Bashar 2019


CHAPTER 05 Saif.io

Note that in Program 5.1 in Line 13 I specified the return type for the main
function as of type int and in Line 23 I added the return 0; statement
as the main function will return the integer zero to the operating system this
will indicate that our program executed and finished successfully.

Matching types

the function’s returned value must match the return


type specified in the function’s implementation, or
you will encounter errors.

5.4 Function Declaration


Function declaration sometimes also called function’s prototype or
function’s signature it is the statement that declare the function to the
program.

As we saw in the previous program we wrote the function above the main
function, this is not mandatory, we can write the function below the main
function but in this case, we have to add the function’s declaration
statement.

The reason behind why we need to declare a function if its written below
the main function, is we know that the compiler read the program from
top to bottom, and if the function’s implementation was below the main
function and the function call was inside the main function, so the
compiler will read the function call before its implementation. Which
means that the compiler does not know anything about the function we
are calling. So, we need to include a declaration before we call a
function, for the compiler to understand what you are calling.

©Saif Bashar 2019


CHAPTER 05 Saif.io

Program 5.1 can also be written like this:

Program 5.2
1 // calculating factorial using function
2 #include<iostream>
3 using namespace std;
4
5 int fact(int);
6
7 int main () {
8 int number;
9 cout<<"Give me a Number: ";
10 cin>>number;
11 cout<<"The Result: "<< fact(number);
12 return 0;
13 } //end of main function
14
15 long fact(int number){
16 long result = 1;
17 for (int i=number; i>1; --i){
18 result *= i;
19 }
20 return result;
21 } //end of fact function

The factorial function’s implementation below the main function and the
prototype added in Line 5.

But however, there is a performance related issue here, when you put a
function’s implementation above the main function it is automatically
considered as inline function, inline functions are faster to run than regular
functions, inline functions save the time required to retrieve a function at
runtime. You can also add the inline keyword before the function’s
return type, to make a function an inline function, this is used for short
functions that the program frequently calls.

©Saif Bashar 2019


CHAPTER 05 Saif.io

The function’s prototype contains the function name and its return type
and the number of arguments it takes and their types and a semi colon
added at the end of the declaration statement.

Function Declaration

returnType functionName(argumentType);

Video lecture: Functions


https://youtu.be/L-5cmL-Edxk

You can also put the prototype inside the main function, but it must be
before the function call.

Header Files

You can also make your own header files that contain the
implementation of your important functions and use the
#include<yourfile> in your programs and start using the
functions you already built, you don’t have to implement the
same function in every program you write. Built it once put it in a
header file and use it in all your programs

©Saif Bashar 2019


CHAPTER 05 Saif.io

5.5 Functions’ Types


We can classify functions according on what they receive as an input
and what they return or not return as an output, as the following diagram
describes functions types:

Functions

Type 1 Type 2 Type 3

Type 1: when the function takes no parameters and don’t return any
value, we specify void as a return type, we can also put void in its
arguments or leave the parenthesis empty, usually functions that don’t
return any value to the function call, they print out the output.

Let us write the factorial program again with a function of this type

Program 5.3
1 // calculating factorial using type 1 function
2 #include<iostream>
3 using namespace std;
4
5 inline void fact(void){
6 int number;
7 long result = 1;
8 cout<<"Give me a Number: ";
9 cin>>number;
10 for(int i=number; i>1; --i){
11 result *= i; }
12 cout<<"The Result: "<<result;
13 }
14
15 int main () {
16 fact();
17 return 0; }

©Saif Bashar 2019


CHAPTER 05 Saif.io

Type 2: when the function takes parameters and don’t return any value,
we specify void as a return type, usually functions that don’t return any
value to the function call, they print out the output.

The factorial program with a function of this type

Program 5.4
1 // calculating factorial using type 2 function
2 #include<iostream>
3 using namespace std;
4
5 inline void fact(int number){
6 long result = 1;
7 for(int i=number; i>1; --i){
8 result *= i; }
9 cout<<"The Result: "<<result;
10 }
11
12 int main () {
13 int number;
14 cout<<"Give me a Number: ";
15 cin>>number;
16 fact(number);
17 return 0; }

Note that the calling of type 1 and type 2 functions, we just mention the
function name with its parameters in a single line, see Line 16 on both
programs Program 5.3 and Program 5.4.

Type 3: when the function takes parameters and return the output to the
function call, this type is the most commonly used by programmers as we
wrote the factorial program using this type see Program 5.1 or Program 5.2.

Note that the calling of type 3 functions, the function come either in an
expression as of Program 5.1 Line 20 or in the cout statement as of
Program 5.2 Line 11.

©Saif Bashar 2019


CHAPTER 05 Saif.io

5.6 Passing Parameters


The input to a function of type 2 or type 3 is passed from the function
call to the function’s implementation. This process is called passing
parameters.

When we call a function like this:

int main(){

int a=90, b=88, c=78;


float v = average(a, b, c);

cout<<v;

return 0;

This means that we are passing a copy of the values of the three variables
a, b and c. The values 90, 88 and 78 are copied and the copies are passed
to the function’s implementation, this process is called sending parameters
by value.

The passed copies will be received by the function’s implementation as


regular variables. We should match the parameter’s number and type, the
function’s implementation should look like this:

float average(int a, int b, int c){

return (a+b+c)/3.0;

The variables in the function implementation will receive the copied values
from the function call in the order they were sent. The a, b, c variables in
the implementation are not the same variables in the main function
although they hold the same values, we can also change the variables

©Saif Bashar 2019


CHAPTER 05 Saif.io

names it won’t affect the program, the following implementation will work
too:

float average(int x, int y, int z){

return (x+y+z)/3.0;

The variables in the main function are called the actual parameters while
the variables in the function implementation are called the formal
parameters.

Another method of passing parameters is when we pass their addresses,


and this is called passing by pointer. We use pointers to store the
addresses.

Here we are passing the addresses:

int main(){

int a=90, b=88, c=78;


float v = average(&a, &b, &c);

cout<<v;

return 0;

Note that the & operator is called the reference operator that returns the
address of a variable which is represented in hexa-decimal, don’t confuse
the unary address operator with the binary bitwise and operator that we
discussed in Chapter 3.

©Saif Bashar 2019


CHAPTER 05 Saif.io

Try to test the reference operator to see that it gives you the variable’s
address in hexa-decimal value:

cout <<&a << endl <<&b;

When we pass an address, we have to store it in a special variable that


store only addresses, this special variable is called a pointer (more about
pointers in Chapter 9), so the implementation of the function will be like
this.

float average(int *a, int *b, int *c){

return (*a + *b + *c)/3.0; }

A pointer indicated by the dereference operator *, don’t confuse the


unary dereference operator with the binary multiplication operator that
we discussed in Chapter 2.

Here a, b and c are pointers that points to the original values of the
variables in the main function.

Another easier way to pass addresses is called passing by reference

float average(int &a, int &b, int &c){

return (a+b+c)/3.0;

int main(){

int a=90, b=88, c=78;


float v = average(a, b, c);

cout<<v;

return 0;

©Saif Bashar 2019


CHAPTER 05 Saif.io

Three ways of passing parameters in C/C++

Passing Parameters

By Value By Reference By Pointer

The deference between the first method (passing by value) and the other
two methods (passing by reference and passing by pointer) is that in the
first method when you pass a parameter by value this mean the original
value will remain the same, any changes on the passed value will affect
only the copied value not the original, let me explain this with an example
that swaps two values.

Program 5.5
1 // swap function pass by value
2 #include<iostream>
3 using namespace std;
4
5 inline void swap(int a, int b){
6 int temp = a;
7 a = b;
8 b = temp;
9 }
10
11 int main () {
12 int a=33, b=66;
13 swap(a, b);
14 cout<<"Numbers after swapping: "<<endl;
15 cout<<"a = "<<a<<endl<<"b = "<<b;
16 return 0; }

©Saif Bashar 2019


CHAPTER 05 Saif.io

The output will be:

Numbers after swapping:


a = 33
b = 66

Note that the original values did not swap because we were swapping the
copies not the original values.

Passing values by reference or by pointer do the opposite, the change is


done on the function will affect the original values in the program, look at
Program 5.6 and Program 5.7.

Program 5.6
1 // swap function pass by pointer
2 #include<iostream>
3 using namespace std;
4
5 inline void swap(int *a, int *b){
6 int temp = *a;
7 *a = *b;
8 *b = temp;
9 }
10
11 int main () {
12 int a=33, b=66;
13 swap(&a, &b);
14 cout<<"Numbers after swapping: "<<endl;
15 cout<<"a = "<<a<<endl<<"b = "<<b;
16 return 0; }

©Saif Bashar 2019


CHAPTER 05 Saif.io

The output will be:

Numbers after swapping:


a = 66
b = 33

You can see that the swap function affected and swapped the original
values in the main function.

Program 5.7
1 // swap function pass by reference
2 #include<iostream>
3 using namespace std;
4
5 inline void swap(int &a, int &b){
6 int temp = a;
7 a = b;
8 b = temp;
9 }
10
11 int main () {
12 int a=33, b=66;
13 swap(a, b);
14 cout<<"Numbers after swapping: "<<endl;
15 cout<<"a = "<<a<<endl<<"b = "<<b;
16 return 0; }

The output will be:

Numbers after swapping:


a = 66
b = 33

©Saif Bashar 2019


CHAPTER 05 Saif.io

So, which way is better? Definitely passing by reference and by pointer is


better because it results in a faster program with better performance
especially when passing large files, passing by value will slow down your
program because it involves coping data and passing them to functions.

Although sometimes you don’t have large chunks of data and you don’t
want your original values to change then passing by value is the correct
choice.

5.7 Function Overloading


The word overloading in programming world means give something
more than one job, function overloading means one function name and
multiple implementations, the correct implementation is executed
according to the number of parameters passed or the return type of a
function.

Let me explain this with an example, let’s build a function that calculate a
volume for a cube and a cylinder. One solution is to write two functions
with different names, the first function to calculate the volume of a cube
and the other one to calculate the volume of the cylinder.

Another solution you can benefit from the feature of function overloading,
by writing two functions with the same name but different parameters.

Program 5.8 below has two functions with the same name but different
number of parameters, this is called function overloading, the function that
calculate the cube’s volume will be executed when we call it and pass to
it only one parameter, see Line 18.

The other volume function that calculate the cylinder volume will be
executed when called and passed to it two parameters see Line 25.

©Saif Bashar 2019


CHAPTER 05 Saif.io

Note that function overloading can happen not only if the number of
arguments is different, it can happen also with the same number of
arguments but different data types, or even different return type, the idea
is the name of the function is fixed but its signatures vary.

Program 5.8
1 // function overloading
2 #include<iostream>
3 using namespace std;
4
5 int volume(int a){
6 return (a * a * a);
7 }
8
9 double volume(int h, int r){
10 const float pi = 3.14;
11 return (pi * r * r * h);
12 }
13
14 int main () {
15 int length, height, radius;
16 cout<<"Give me the cube length: ";
17 cin>>length;
18 cout<<"Cube volume: "<<volume(length)<<endl;
19
20 cout<<"Give me the cylinder height: ";
21 cin>>height;
22 cout<<"Give me the cylinder radius: ";
23 cin>>radius;
24 cout<<"Cylinder volume: ";
25 cout<<volume(height, radius);
26
27 return 0;
28 }

Video lecture: Important Notes on Functions


https://youtu.be/L6_4yx4Nx-s

©Saif Bashar 2019


CHAPTER 05 Saif.io

5.8 Default Arguments


We can specify default arguments for a function in the function’s
implementation, when we specify the default argument it will be assigned
to the parameter if we don’t pass one to the function, for example, if we
have a function that print a message, implemented as follows:

void print(string msg="Hello from default argument"){

cout<<msg;
}

Now if we call it and pass a parameter to it like this:

string msg = "Hello from main function";


print(msg);

The output will be:

Hello from main function

But when we call it and don’t pass anything:

print();

The output will be:

Hello from default argument

The default argument will give the value to the msg variable.

Video lecture: Default Arguments


https://youtu.be/LPwvSEfHk8M

©Saif Bashar 2019


CHAPTER 05 Saif.io

5.9 Global & Local Variables


We learned about variables in Chapter 1 and we saw there are a lot
of things related to variables, a variable has name, value, address, size,
range and a data type. We also learned that a variable has a storage
specifier.

Now I want to tell that a variable also has a life or a scope, the variable is
born or created we you declare it, and dies when its scope ends, for
example if you declare a variable in main function it will be created in
memory and dies when the program reaches the return 0; statement.

We can create scopes inside other scopes using the curly braces, check
the following program:

Program 5.9
1 // variable scope
2 #include<iostream>
3 using namespace std;
4
5 int main () { // start of main function scope
6 int var = 10;
7
8 { // new internal scope
9 int var = 50;
10 cout<< var <<endl;
11 } // end of internal scope
12
13 cout<< var <<endl;
14
15 return 0;
16 } // end of main function scope

©Saif Bashar 2019


CHAPTER 05 Saif.io

Program 5.9 has two variables named var, you might think they are the
same but they are not, they have the same name but different scopes,
they two separate variables.

The variable var created at Line 6 will die at Line 15, and the cout in Line
13 will print its value which is 10.

While the second variable var is another variable stored in different


location in memory created at a new scope in Line 9 and died at Line 11
when its scope ended, so the cout in Line 10 will print 50 the value of var
in this scope, not the value of the other var in the outer scope.

We have seen that functions contain curly braces this mean every function
have a scope of its own, when a function is called and parameters are
passed, the functions variables are created in memory and deleted when
the function’s scope ends. The variables inside a function’s scope are
called local variables, and can be accessed only inside the function.

We can define global variables above the main function and they can be
accessed anywhere in the program and they die when the program ends,
see the following program:

Program 5.10
1 // global variables
2 #include<iostream>
3 using namespace std;
4
5 string name = "saif";
6
7 int main () {
8 cout<<"Program written by: "<< name;
9 return 0;
10 }

©Saif Bashar 2019


CHAPTER 05 Saif.io

Program 5.10 has a global variable name declared top of the main function
and printed inside the main function, it also can be accessed from any
other function in the program.

Note that if you have two global variables of the same name in two
different files, then you included one file into the other file, you will have
duplicate variables with the same name. in this scenario we can use the
extern keyword to refer to the variable in the included file.

Chapter 2 also introduced you to the auto keyword as the default state of
a variable, if we create a variable inside a function it is called a local
variable and an automatic variable, it will be created every time we call
the function and deleted when the function ends at each call.

There is another type of variables that are created at the first function call
only and live as long as the program is running these are called static
variables, we can create a static variable by using the keyword static in
its declaration.

Program 5.11
1 // static vs automatic
2 #include<iostream>
3 using namespace std;
4
5 void Myfunc(){
6 int a=10; //automatic variable
7 a++;
8 cout<<"a= "<<a<<endl;
9 static int b=20; //static variable
10 b++;
11 cout<<"b= "<<b<<endl; }
12
13 int main () {
14 Myfunc();
15 Myfunc();
16 Myfunc();
17 return 0; }

©Saif Bashar 2019


CHAPTER 05 Saif.io

The main function in Program 5.10 has three function calls to a function
called Myfunc(), this function has two variables an automatic variable a
that will be created and deleted three times and a static variable b that
will be created once at the first call and deleted once when the program
ends.

The output of Program 5.11

a= 11
b= 21
a= 11
b= 22
a= 11
b= 23

Don’t confuse const with static, because const mean the value is
constant and cannot be change, while static means the variable’s
existence is not changing while we can change its value.

Video lecture: More about Variables


https://youtu.be/lHtqEwR65c8

©Saif Bashar 2019


CHAPTER 05 Saif.io

5.10 Recursion
We have seen that we can call a function from the main
function or from any other function. But when a function calls itself it’s
called a recursive function.

Recursive functions are useful in writing complex program especially in


data structures. Recursive function is a form of looping mechanism, we
cannot let a function keep calling itself indefinitely because the program
will enter an infinite loop then crashes.

Recursive functions like loops they need a stop condition called a base
case that stops the function from calling itself.

For example, if we want to print the numbers from 10 to 1 without using


loops we can do that using recursion see the following program.

Program 5.12
1 // recursion
2 #include<iostream>
3 using namespace std;
4
5 void print(int counter){
6
7 cout<<counter<<endl;
8
9 if (counter == 1)
10 return 0;
11 else
12 print(--counter);
13 }
14
15 int main () {
16 print(10);
17 return 0;
18 }

©Saif Bashar 2019


CHAPTER 05 Saif.io

We can also write the factorial program using recursion, note that
recursion takes more memory space.

Program 5.13
1 // factorial in recursion
2 #include<iostream>
3 using namespace std;
4
5 long fact(int number){
6
7 if(number == 1)
8 return 1;
9 else
10 return number * fact(number - 1);
11 }
12
13 int main () {
14 int number;
15 cout<<"Give me a Number: ";
16 cin>>number;
17
18 cout<<"The Result: "<<fact(number);
19 }
20

The program execution will follow this pattern, if the number was 5 then:

fact(5) = 5 * fact(4)
fact(4) = 4 * fact(3)
fact(3) = 3 * fact(2)
fact(2) = 2 * fact(1)
fact(1) = 1

©Saif Bashar 2019


CHAPTER 05 Saif.io

Then the function calls will back track to calculate the final result,

fact(2) = 2
fact(3) = 6
fact(4) = 24
fact(5) = 120

The finale result is 120 will be returned to the function call in the main
function to be printed on screen.

Another example is raising a number to an exponent using recursion

Program 5.14
1 // power in recursion
2 #include<iostream>
3 using namespace std;
4
5 long pwr(int base, int exp){
6
7 if(exp <= 1)
8 return base;
9 else
10 return base * pwr(base, exp - 1);
11 }
12
13 int main () {
14 int base, exp;
15 cout<<"Enter Base: ";
16 cin>>base;
17 cout<<"Enter Exponent: ";
18 cin>>number;
19 cout<<"The Result: "<<pwr(base, exp);
20 return 0; }

Video lecture: Recursion


https://youtu.be/lHtqEwR65c8

©Saif Bashar 2019


CHAPTER 05 Saif.io

Exercises 5
Q1: Write a program that solve the following math series using functions
1 1 1 1
𝑦 =1− + − + ⋯…
2! 3! 4! 𝑛!
Video lecture: Solution for Q1 - Exercises 5
https://youtu.be/-IdNgzepkL4

Q2: Write a program using function that count uppercase letters, in 20


letters entered by the user in the main function
Video lecture: Solution for Q2 - Exercises 5
https://youtu.be/dQEGcsoV9_I

Q3: Write a program using function that reads two integers (feet and
inches) representing distance, then convert this distance to meters.

1 foot = 12 inch
1 inch = 2.54 cm
Video lecture: Solution for Q3 - Exercises 5
https://youtu.be/XxQayunYdlU

Q4: Write a program using function that reads an integer (T) representing
time in seconds, then convert it to the equivalent hours, minutes and
seconds in this form: Hour : Minute : Second
Video lecture: Solution for Q4- Exercises 5
https://youtu.be/PD2tMCSFg1o

Q5: Write a program using function to see if a number is an integer (odd or


even) or not an integer
Video lecture: Solution for Q5- Exercises 5
https://youtu.be/m0NYp2CPQm8

©Saif Bashar 2019


CHAPTER 05 Saif.io

Q6: Write a program using function to input student average and return:
4 if the average between 90-100
3 if the average between 80-89
2 if the average between 70-79
1 if the average between 60-69
0 if the average is lower than 60
Video lecture: Solution for Q6- Exercises 5
https://youtu.be/K08iwf2TWuY

Q7: Write a program using function to find the permutation of n


Video lecture: Solution for Q7- Exercises 5
https://youtu.be/b01jTq_uk7U

Q8: Write a program using function to find the nth Fibonacci number
Video lecture: Solution for Q8- Exercises 5
https://youtu.be/pqBiu4CSClQ

Q9: Write a program using function to calculate the factorial of an integer


entered by the user in the main function
Video lecture: Solution for Q9- Exercises 5
https://youtu.be/CtdrgpRZIQE

Q10: Write a program using function to evaluate the following equation


𝑥! − 𝑦!
𝑍=
(𝑥 − 𝑦)!

Video lecture: Solution for Q10- Exercises 5


https://youtu.be/Rlh9WD7qFHc

©Saif Bashar 2019


CHAPTER 05 Saif.io

Q11: Write a program using function to test the year if it is a leap year or
not
Video lecture: Solution for Q11- Exercises 5
https://youtu.be/77V_xoV93SQ

Q12: Write a program using function to fine 𝑥 𝑦


Video lecture: Solution for Q12- Exercises 5
https://youtu.be/tk9urKJrj6Q

Q13: Write a program using function to reverse an integer number


Video lecture: Solution for Q13- Exercises 5
https://youtu.be/o3o2gGvqKeA

Q14: Write a program using function to convert any character from capital
to small or from small to capital
Video lecture: Solution for Q14- Exercises 5
https://youtu.be/pPV5mmu9LzQ

Q15: Write a program using recursive function to find power of n numbers


Video lecture: Solution for Q15- Exercises 5
https://youtu.be/VbnKWF32MWo

©Saif Bashar 2019


Chapter 06
Arrays
6.1 Introduction
6.2 One-Dimensional Arrays
6.3 Multi-Dimensional Arrays
Exercises 6

s a i f . i o
CHAPTER 06 Saif.io

6.1 Introductions
Till now we learned about simple or primitive data types, we
learned about variables, and as we saw that a variable represents a
single location in memory that have many things that we talked
about in the previous chapters, a variable can represent only one
value, what if we want a variable that represent many values and
several locations?

An Array is like a variable that can represent many values, or think


about it as a list of variables. Arrays are very useful and commonly
used data structure. We can put values of similar type in an array for
example the temperatures for a month, it is more logical to create a
single array with 30 location, than we define 30 variables.

The formal definition of an array it is: a collection of ordered and


finite data elements of the same type stored in consecutive locations
in memory.

The important things you need to remember:

- Arrays have dimensions


- Arrays have a fixed size that represent the number of elements
- Arrays have elements and indices
- Arrays stored in consecutive locations
- Arrays’ elements are of the same type
- Arrays are considered the simplest data structure

Data structures is a stand-alone course that you should take after


you learn the basics of procedural and object-oriented
programming.

©Saif Bashar 2019


CHAPTER 06 Saif.io

6.1 One-Dimensional Arrays


Arrays have dimensions and each dimension should have a
fixed size, the simplest array is the one-dimensional array. Think of it as
a series of consecutive memory locations.

We can define an array the same way we defined a variable but we


have to give the array a size to its dimension. To specify a size we
need to use a new pair of brackets called the square brackets [ ]
these brackets are use only with arrays.

Defining an Array

dataType arrayName[size];

Defining an array called a with five integer elements, the code will
be like this:

int a[5]; //an array with five elements


int b; // a variable holds a single value

Naming an array also follow the rules of naming an identifier that we


discussed in Chapter 2, in memory the locations will look like the
following figure:

Note that to access any element we need an index, the


index of arrays in C/C++ starts with zero so to access the
first element we specify the name of the array then the
index of the first location a[0], to access the third
element a[2].

A common mistakes new programmers do is if they try to


access the last element they use a[5] which is wrong
since the last element of five element array have an
index 4 so to access it you should write a[4].

©Saif Bashar 2019


CHAPTER 06 Saif.io

Trying to use a[5] means access a location outside the array’s


boundary and it will give you a random value.

Also, you should note that printing an array without initialize it with
values it will give you random values, the same thing is with variables.
So, you have to initialize your array or give it values before starting to
work with it.

You can initialize an array either directly or using loops with cin
function, initializing an array directly you have to use curly braces
because you have more than one value.

int a[5]={10,20,30,40,50}; // array initialization


int b=10; // variable initialization

Now after you initialized the array the following code will give you
what you expect:

cout<<a[0]<<endl;
cout<<a[1]<<endl;
cout<<a[2]<<endl;
cout<<a[3]<<endl;
cout<<a[4]<<endl;

the output will be:

10
20
30
40
50

Note if we initialize the array like this:

int a[5]={10,20,30};

©Saif Bashar 2019


CHAPTER 06 Saif.io

The fourth and the fifth elements will take a value of zero, so if we
want to initialize and array and give all its elements the value of zero
you can do something like this:

int a[5]={0};

There is another more efficient way to work with arrays is by using


loops, printing an array can be done like this:

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


cout<<a[i]<<endl;

Note that the loop’s counter started with zero, and ended with 4 as it
is the index of the last element.

The second way of initializing an array is by using cin

cin>>a[0];
cin>>a[1];
cin>>a[2];
cin>>a[3];
cin>>a[4];

Using loops is always better:


for(int i=0; i<5; i++)
cin>>a[i];

©Saif Bashar 2019


CHAPTER 06 Saif.io

A complete program that define, initialize and print an array will be


like the following program:

Program 6.1
1 // working with arrays
2 #include<iostream>
3 using namespace std;
4 int main () {
5 int a[5]={10,20,30,40,50};
6
7 cout<<"Give me a Five Numbers: ";
8 for(int i=0; i<5; i++)
9 cin>>a[i];
10
11 cout<<"Here is the array elements: ";
12 for(int i=0; i<5; i++)
13 cout<<a[i]<<endl;
14 return 0;
15 }

A good practice is to define the array dimension’s size as a constant


variable like so:

const int size = 5;


int a[size]={0};

or use the preprocessor directive under the #include you can write:

#define size 5

©Saif Bashar 2019


CHAPTER 06 Saif.io

Like variables arrays also can be sent to functions as parameters, the


program above can be written using functions:

Program 6.2
1 // arrays with functions
2 #include<iostream>
3 #define size 5
4 using namespace std;
5
6 void read(int a[size]){
7 cout<<"Give me a Five Numbers: ";
8 for(int i=0; i<size; i++)
9 cin>>a[i];
10 }
11
12 void print(int a[size]){
13 cout<<"Here is the array elements: ";
14 for(int i=0; i<size; i++)
15 cout<<a[i]<<endl;
16 }
17
18 int main () {
19 int a[size]={10,20,30,40,50};
20 read(a);
21 print(a);
22 return 0;
23 }

Note that when we pass an array to a function we type just the


name of the array, but when we receive an array in the function’s
implementation we have to put square brackets with the size in
some cases. Passing arrays always is by reference because the array
name represents the address of the first element in the array. This
mean if we pass an array to a function and the function changed
the elements of the array, this change will be reflected in the array in
the whole program.
Video lecture: Arrays
https://youtu.be/4vIZq4Vfmt8

©Saif Bashar 2019


CHAPTER 06 Saif.io

6.2 Multi-Dimensional Arrays


We can always add more dimensions to an array, two-
dimensional arrays or matrices are heavily used in image processing
applications, cryptography and many other computer’s fields.

You can define a two-dimensional array by specifying the two


dimensions sizes.
int a[2][2];

The code above will create a matrix that have 4 elements, 2 rows
and 2 columns. You can calculate the number of elements in multi-
dimensional arrays by multiplying the dimensions.

Although the memory cells are arranged in sequential form you can
think of a two-dimensional array as a rectangular matrix

Two-dimensional arrays have two indices, one to specify the row and
the other is to specify the column

Initializing a two-dimensional array also can


be done directly or by using cin but it
requires two loops since it have two indices,
see the following code:
int a[2][2]={
{10,20},
{30,40}
};

Or like this:
int a[2][2]={10,20,30,40};

Or initializing the array at runtime:


for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
cin>>a[i][j];

©Saif Bashar 2019


CHAPTER 06 Saif.io

Always use a new index for each loop, here i is the index of the row,
and j is the index of the column, so a[0][1] means the cell location
at row 0 and column 1

Printing a two-dimensional like rectangle:


for(int i=0; i<2; i++)
for(int j=0; j<2; j++){
cout<<a[i][j];
cout<<endl;
}

There are some operations that we can perform on a square matrix,


square matrix when the number of rows equals to the number of
columns, these operations like finding the main diagonal, secondary
diagonal, upper triangle, lower triangle and so on.

Let’s take a 3*3 square matrix as an example:

0,0 0,1 0,2


1,0 1,1 1,2 Main Diagonal
2,0 2,1 2,2

0,0 0,1 0,2


1,0 1,1 1,2 Secondary Diagonal
2,0 2,1 2,2

0,0 0,1 0,2


1,0 1,1 1,2 Upper Triangle
2,0 2,1 2,2

0,0 0,1 0,2


1,0 1,1 1,2 Lower Triangle
2,0 2,1 2,2

©Saif Bashar 2019


CHAPTER 06 Saif.io

By looking at the values of the two indices we can make conditions


to extract the elements we want:

Main diagonal when i==j


Secondary diagonal when i+j==2
Upper triangle when i<j
Lower triangle when i>j

We can also use functions to do that see Program 6.3

Program 6.3
1 // 2D arrays with functions
2 #include<iostream>
3 using namespace std;
4
5 void mainDiagonal(int a[2][2]){
6 for(int i=0; i<5; i++)
7 for(int i=0; i<5; i++)
8 if(i==j)
9 cout<<a[i][j];
10 }
11
12 void upperTriangle(int a[2][2]){
13 for(int i=0; i<5; i++)
14 for(int i=0; i<5; i++)
15 if(i<j)
16 cout<<a[i][j];
17 }
18
19 int main () {
20 int a[2][2]={10,20,30,40};
21 mainDiagonal(a);
22 upperTriangle(a);
23 return 0;
24 }

©Saif Bashar 2019


CHAPTER 06 Saif.io

You can also define three-dimensional arrays that have three indices
like so:
int a[2][4][3];

you can add as many dimensions as you want as the problem you
are trying to solve requires.

Video lecture: Multi-Dimensional Arrays


https://youtu.be/lqVYEcaijyM

©Saif Bashar 2019


CHAPTER 06 Saif.io

Exercises 6
Q1: Write a program using function to find the summation of
student’s marks and average (for 8 marks)
Video lecture: Solution for Q1 - Exercises 6
https://youtu.be/i-iypPYK3aA

Q2: Write a program using function to find the array’s elements are in
order or not
Video lecture: Solution for Q2 - Exercises 6
https://youtu.be/uCpBlMysBLM

Q3: Write a program using function to calculate the number of zeros


in the array
Video lecture: Solution for Q3 - Exercises 6
https://youtu.be/UhYrbxwUQUc

Q4: Write a program using function to add two one-dimensional


arrays
Video lecture: Solution for Q4 - Exercises 6
https://youtu.be/RGI0jb83A2A

Q5: Write a program using function to multiply the array elements by


two
Video lecture: Solution for Q5 - Exercises 6
https://youtu.be/ZcX3ppZjJVE

©Saif Bashar 2019


CHAPTER 06 Saif.io

Q6: Write a program using function to read temperatures of 30 days


and calculate their average
Video lecture: Solution for Q6 - Exercises 6
https://youtu.be/Mnz_HxeYYEI

Q7: Write a program using function to merge two arrays in one array
Video lecture: Solution for Q7 - Exercises 6
https://youtu.be/sL_10dRliZY

Q8: Write a program to read 3*4 2D array then find the summation of
each column
Video lecture: Solution for Q8 - Exercises 6
https://youtu.be/XpicL_ihgb0

Q9: Write a program to replace each element in the secondary


diagonal with zeros
Video lecture: Solution for Q9 - Exercises 6
https://youtu.be/cvGvDi1a-4k

Q10: Write a program to replace the elements of the main diagonal


with the elements of the secondary diagonal
Video lecture: Solution for Q10 - Exercises 6
https://youtu.be/i6q_vMmzjJg

Q11: Write a program to find the summation of odd numbers in 2D


array
Video lecture: Solution for Q11 - Exercises 6
https://youtu.be/7it9bFl1lEc

©Saif Bashar 2019


CHAPTER 06 Saif.io

Q12: Write a program to search for a value in 2D array and print its
location
Video lecture: Solution for Q12 - Exercises 6
https://youtu.be/PlPK-o9v0as

Q13: Write a program to convert a 1D array to 2D array


Video lecture: Solution for Q13 - Exercises 6
https://youtu.be/mRHEF9yKDkQ

Q14: Write a program to read A[n][n] of characters then find array B


and array C such that B contains only capital letters and C with only
small letters
Video lecture: Solution for Q14 - Exercises 6
https://youtu.be/udM1Z3Bb1vI

Q15: Write a program to read A[n][n] of numbers then put 10 instead


of each even positive number
Video lecture: Solution for Q15 - Exercises 6
https://youtu.be/eXQzsZXzq_Q

Q16: Write a program to read A[n][n] of numbers then put 10 instead


of each even positive number in the main diagonal
Video lecture: Solution for Q16 - Exercises 6
https://youtu.be/992R9XRYa1o

Q17: Write a program to read A[n][n] of numbers then find the


minimum number in the array
Video lecture: Solution for Q17 - Exercises 6
https://youtu.be/-oGg_AEkEeM

©Saif Bashar 2019


CHAPTER 06 Saif.io

Q18: Write a program to exchange row1 and row3 in 4*3 array


Video lecture: Solution for Q18 - Exercises 6
https://youtu.be/MtbaTIAPDws

Q19: Write a program to exchange row0 with col3 in 4*4 array


Video lecture: Solution for Q19 - Exercises 6
https://youtu.be/uu-VGdsIGIk

Q20: Write a program to find the greatest number in the secondary


diagonal in 3*3 array
Video lecture: Solution for Q20 - Exercises 6
https://youtu.be/6MVX7qvulQ8

Q21: Write a program to read x[n] and rotate the elements to the left
by one position
Video lecture: Solution for Q21 - Exercises 6
https://youtu.be/X9p70lrnX2k

Q22: Write a program to read A[n] and a location Z then delete the
number at location Z from the array and print the new array
Video lecture: Solution for Q22 - Exercises 6
https://youtu.be/FwUglkTlr7Q

Q23: Write a program to sort an array in ascending and descending


order
Video lecture: Solution for Q23 - Exercises 6
https://youtu.be/w_Fu8TiJJAY

©Saif Bashar 2019


CHAPTER 06 Saif.io

Q24: Write a program to read A[n] and find the average of the even
numbers in it
Video lecture: Solution for Q24 - Exercises 6
https://youtu.be/LmDLUm84zvM

Q25: Write a program to create array b from a

1 2 3 6
𝑎=4 5 6 𝑏 = 15
7 8 9 24

Video lecture: Solution for Q25- Exercises 6


https://youtu.be/CcZa_UcKf-c

Q26: Write a program to create the following arrays

1 1 1 1 2 1 1 1
2 2 2 2 1 2 1 1
𝑎= 𝑏=
3 3 3 3 1 1 2 1
4 4 4 4 1 1 1 2

Video lecture: Solution for Q26- Exercises 6


https://youtu.be/o1bXUgHSFwg

©Saif Bashar 2019


Chapter 07
Strings
7.1 Introduction
7.2 String Definition
7.3 String Functions
7.4 Conversion Functions
7.5 String Data Type
Exercises 7

s a i f . i o
CHAPTER 07 Saif.io

7.1 Introduction
We have seen in the previous chapters the string literals that
was surrounded by double quotes and I introduced you to the
string as a basic data type, this is true for the C++ language but in
C language a string is represented as an array of characters. We
have seen in the previous chapter the array which is a collection of
data of the same type, so a series of characters are called a string.

7.2 String Definition

Strings are useful to store names, addresses, emails or any textual


information that we need in our programs, we can use an array of
characters to store textual information:

Declaring and initializing and array of characters:

char name[4]={’s’,’a’,’i’,’f’};

We can print all the array’s elements by using the array’s name only:

cout<< name;

The output will be saif and some additional letters! so why we got
these weird letters ?, the answer to this when you try to print out an
array of characters, the cout will keep printing letters until it reaches
a null value in memory to stop. Because the null character is a
special character that terminate a string.

The proper declaration and initialization of a string should include the


null character \0 :

char name[5]={’s’,’a’,’i’,’f’,’\0’};

©Saif Bashar 2019


CHAPTER 07 Saif.io

Note the size of the array now is five, so, if you have an array of
characters that ends with the null character then it’s called a string
otherwise it’s just an array of characters and not a string.

You can also declare and initialize strings like this:

char name[5]="saif";

The null character will be added at the end of the string


automatically.

We can also read a string using array of characters, so if we define


an array of characters like this:

char name[12];
cin>>name;

cout<<name;

If we gave this string saif bashar at runtime, the cin will take only
the first four letters and it will not take the space and the second
word, if we want to read a string with spaces included we have to
use the cin.getline() function like the following piece of code:

char name[12];
cin.getline(name, 12);

cout<<name;

cin.getline() is a function that takes two arguments, the array of


character and its size.

©Saif Bashar 2019


CHAPTER 07 Saif.io

7.3 String Functions


There are a group of functions that deals with strings (as an
array of characters) these built-in functions are included in a library
called string.h so in order to use these functions you need to add
the following statement to your program:

#include <string.h>

Some of these functions are listed below:

strlen(): This functions takes an array of characters as an


input and returns the number of characters, the null character is not
counted, so it is simply measure the length of a string.

strcpy( , ): This functions takes two inputs as an array of


characters and it copy the second argument in the first argument so
the following code:

char name1[4]= "Ali";


char name2[6]= "Ahmed";

strcpy(name1, name2);

cout<<name1<<endl; //name1 = Ahmed


cout<<name2; //name2 = Ahmed

Note that the old value of the first argument will be lost and replaced
by the value of the second argument.

©Saif Bashar 2019


CHAPTER 07 Saif.io

strcat( , ): This functions takes two inputs as an array of


characters and it copy the second argument and attach it
(concatenate) to the first argument so the following code:

char name1[4]= "Ali";


char name2[6]= "Ahmed";

strcat(name1, name2);

cout<<name1<<endl; //name1 = AliAhmed


cout<<name2; //name2 = Ahmed

The old value of the first argument Ali will be concatenated with the
value of the second argument Ahmed to produce the string
AliAhmed.

strcmp( , ): This function takes two inputs as an array of


characters and compare them and return an integer value:

- Return 1 if the first argument is greater than the second


argument.

- Return -1 if the first argument is smaller than the second


argument.

- Return 0 if the first argument is equal to the second


argument.

char name1[4]= "Ali";


char name2[6]= "Ahmed";
char name3[5]= "Saif";
char name4[7]= "Zainab";
char name5[6]= "Ahmed";

cout<<strcmp(name1, name2)<<endl;
cout<<strcmp(name3, name4)<<endl;
cout<<strcmp(name2, name5)<<endl;

©Saif Bashar 2019


CHAPTER 07 Saif.io

Note that the first output will be 1 because name1 is greater than
name2, I know Ali have less letters than Ahmed but this function work
on ASCII codes not on the number of characters. And it compares
letters one by one, so since the L in Ali is larger than the H in Ahmed,
so name1 is bigger.

The second output will be -1 because name3 is smaller than name4

The third output will be zero since both strings are equal.

Video lecture: Strings


https://youtu.be/d02MwEtOUis

©Saif Bashar 2019


CHAPTER 07 Saif.io

7.4 Conversion Functions


We’ve seen some built-in conversion functions in Chapter 2 that
convert from a character to an ASCII code and vice versa namely
the int() and char() functions.

There are many other functions that are built in the stdlib.h library
that also can convert types, the most commonly used are listed
below:

atoi(): This function converts a string to an integer, it takes one


input as an array of characters and returns its equivalent integer
number, the function’s name means alpha to integer

char strYear[5]= "2019";


int year = atoi(strYear);

The variable year will hold the integer value of 2019.

atof(): This function converts a string to float, it takes one input


as an array of characters and returns its equivalent float number, the
function’s name means alpha to float

char strPi[5]= "3.14";


float pi = atof(strPi);

The variable pi will hold the float value of 3.14.

atol(): this function converts a string to long, it takes one input


as an array of characters and returns its equivalent long number, the
function’s name means alpha to long

char strHuge[11]= "1000000000";


long Huge = atol(strHuge);

©Saif Bashar 2019


CHAPTER 07 Saif.io

itoa(): This function converts an integer to a string, it takes


three arguments as an input, the first argument is the integer number
we want to convert, the second argument is the array of characters
to store the number digits and the last argument will represent the
base (10 for decimal, 8 for octal, 2 for binary, 16 for hexa-decimal),
the function’s name means integer to alpha

char str[]= "";


int number = 1234;
itoa(number, str, 10);

Video lecture: Conversion Functions


https://youtu.be/IbCQrnPFbpE

©Saif Bashar 2019


CHAPTER 07 Saif.io

7.5 String Data Type


It’s always good to follow the updates of programming
languages and use the new features since it makes our
programming experience more productive and efficient.

You don’t have to use arrays in order to work with strings, you can
use the string data type it is much easier:

string name;
cin>>name;

cout<<name;

Reading a string with spaces also we have to use the getline


function in this syntax:

string name;
getline(cin, name);

cout<<name;

You can use the + operator to concatenate strings:

string firstName, lastName, fullName;

firstName = "Salman";
lastName = "Khan";
fullName = firstName + lastName;

cout<<fullName; //SalmanKhan

©Saif Bashar 2019


CHAPTER 07 Saif.io

Exercises 7
Q1: Write a program to print a string, then print it character by
character in reverse order
Video lecture: Solution for Q1 - Exercises 7
https://youtu.be/40H8JA5EUm4

Q2: Write a program to check each character in a string and


convert it to lower case if it is an uppercase and convert it to
uppercase if it is a lower case
Video lecture: Solution for Q2 - Exercises 7
https://youtu.be/wrK-T-LuOn4

Q3: Write a program to read a sentence and print its words


separately
Video lecture: Solution for Q3 - Exercises 7
https://youtu.be/uNwYTcfLXwY

Q4: Write a program to check a string if it is a palindrome string or not


Video lecture: Solution for Q4 - Exercises 7
https://youtu.be/JTiUnQCiNeI

©Saif Bashar 2019


Chapter 08
Structures
8.1 Introduction
8.2 Structure’s Definition
8.3 Structure of Structure
8.4 Array of Structures
Exercises 8

s a i f . i o
CHAPTER 08 Saif.io

8.1 Introduction
We have learned so far if we want to store a single value we
use variables, and if we have many values of the same type we use
an array. What if we want to store multiple values of different data
types?

Structures in C/C++ languages provide a construct that let us store


values of different data types, the concept of a structure is similar to
the concept of a record in a table, for example a student’s
information table may contain several fields of different data types
like (id as integer, name as string, age as integer, address as string,
average as float) and so on. We can represent the student using a
structure.

The keyword struct is used to define structures, the structure’s size in


memory is dependent on the number of its members and their types.

Structures are considered a user defined data type UDT

8.2 Structure Definition


We declare structures above the main function, the syntax of
declaring a structure is:

Structure Declaration Syntax

struct structName {
dataType member1;
dataType member2;
dataType member3;
};

©Saif Bashar 2019


CHAPTER 08 Saif.io

Back to the student’s information example we can define a structure


that represent a student with the members (id, name, age, address
and three marks)

struct student{
int id;
string name;
int age;
string address;
float mark1;
float mark2;
float mark3;
};

This structure can be applied to all students in a classroom, if we


want to give it values for individual students then we have to declare
instances form this structure, we have two ways of declaring
instances, the first method creating instance in the structure’s
declaration construct, like the following syntax:

Structure’s Instance Declaration Syntax

struct structName {
dataType member1;
dataType member2;
dataType member3;
}instance1, instance2, instance3;

The second method is much simpler, we can declare instances inside


the main function the same way we used to declare variables, like
the following syntax:

©Saif Bashar 2019


CHAPTER 08 Saif.io

Structure’s Instance Declaration Syntax

structName instance1, instance2, instance3;

After defining an instance that will represent one student, we can


give values to its members using the dot operator, like the following
syntax.

Instance Member’s Syntax


instance1.memebr1 = value;
instance1.memebr2 = value;
instance1.memebr3 = value;

So, we can declare a student instance from our structure and give it
values like the following piece of code:

student noor;
noor.id = 1;
noor.name = "noor";
noor.age = 20;
noor.address = "Baghdad";
noor.mark1 = 85.6;
noor.mark2 = 82.3;
noor.mark3 = 77.6;

We can also send structures to functions as arguments, we better


send them by reference, because sometime structures hold large
data and sending the structure by value will cost a lot of copying.
Sending structures by reference makes our programs much faster.

©Saif Bashar 2019


CHAPTER 08 Saif.io

Program 8.1 working with structures

Program 8.1
1 // structures with functions
2 #include<iostream>
3 using namespace std;
4
5 struct student{
6 long id;
7 string name;
8 int age;
9 string address;
10 float mark1;
11 float mark2;
12 float mark3;
13 };
14
15 float avg(student s){
16
17 return (s.mark1+s.mark2+s.mark3)/3.0;
18 }
19
20 int main () {
21 student sara;
22 sara.id = 1003;
23 sara.name = "Sara";
24 sara.age = 22;
25 sara.address = "Baghdad";
26
27 cout<<"Give me three marks: ";
28 cin>>sara.mark1>>sara.mark2>>sara.mark3;
29
30 cout<<"The Average: "<<avg(sara);
31
32 return 0;
33 }

©Saif Bashar 2019


CHAPTER 08 Saif.io

8.3 Structure of Structure


Nesting is everywhere in programming, we can always put a
structure inside another structure as your program needs, if we take
the previous student structure and try to put inside it a date structure
that hold three members (day, month, year) for example the code
will be something like this:

struct date{
int day;
int month;
int year;
};

struct student{
long id;
string name;
date birthdate;
int age;
string address;
float mark1;
float mark2;
float mark3;
};

Note that if we have nested structures we have to put the inner


structure above the outer structure, and if we want to give it values
we have to use the dot operator twice, like so:

sara.birthdate.day = 18;
sara.birthdate.month = 1;
sara.birthdate.year = 1999;

Video lecture: Structures


https://youtu.be/5Mx9Utynxx0

©Saif Bashar 2019


CHAPTER 08 Saif.io

8.4 Array of Structures


The previous definition for our student structure we created one
instance to represent one student, what if we want to create three
instances for three students, this can be done easily like this:

student saif, ali, ahmed;

Then we can give values to each of the instances’ members, but


what if we wanted to represent 100 students? An Array to the rescue.

We can represent as many instances as we want using arrays with


the same syntax that we used to, but the type of the array will be a
structure, so our example to create 100 students, the code will look
something like this.

student students[100];

Accessing the first student it will be of index zero as you remember


that arrays starts with zero.

students[0].id = 10;
students[0].name = "Mohammed";

We also use loops with arrays

for(int i=0; i<=100; i++){


cout<<"Enter student ID: ";
cin>>students[0].id;
cout<<"Enter student name: ";
cin>>students[0].name;
}

Video lecture: Array of Structures


https://youtu.be/8E-9VhVSun8

©Saif Bashar 2019


CHAPTER 08 Saif.io

Exercises 8
Q1: Write a program that declare a structure for employees that
have the following members: (Name, Age, Address, Phone number
and Country)

Then read and print the information for 100 employees


Video lecture: Solution for Q1 - Exercises 8
https://youtu.be/SKDq2DroaBg

Q2: Write a program that define the following structures:

o Info
▪ ID
▪ Name
▪ Age
o Home
▪ Street
▪ City
▪ State
o Birthdate
▪ Day
▪ Month
▪ Year
o StartDate
▪ Day
▪ Month
▪ Year

Then print only employees whose ID number is less than 100


Video lecture: Solution for Q2 - Exercises 8
https://youtu.be/awDEIth4z08

©Saif Bashar 2019


CHAPTER 08 Saif.io

Q3: write a program to read information of 10 employees and


display this information when entering the employee’s number

Employee

Code (integer)
Name (string)
Gender (EDT)
Degree (EDT)
Video lecture: Solution for Q3 - Exercises 8
https://youtu.be/qfVb_YHo48Y

©Saif Bashar 2019


Chapter 09
Pointers
9.1 Introduction
9.2 Pointers as Functions’ Arguments
9.3 Pointers with Arrays
9.4 Pointers with Structures
Exercises 9

s a i f . i o
CHAPTER 09 Saif.io

9.1 Introduction
C/C++ provide useful tools for the programmer to work directly
with the computer memory, the programmer can access the
addresses of variables and data structures in the program, we have
seen pointers in Chapter 5 when we talked about passing
parameters by pointer. And we have learned that a pointer is a
special variable that store addresses, we use the star * to declare a
pointer. And to access the address we use the reference operator &.

Note that a pointer must have the same type of the value that it
points to, declaring and initializing a pointer in C/C++:

int p=10; //variable


int *ptr; //pointer
ptr = &p; //ptr pointing to 10
cout<<*ptr; //prints 10

The side figure shows that ptr is a pointer that hold the
variable’s p address in memory.

Note that memory addresses are represented in


hexadecimal number system.

Pointers are used to create dynamic variables stored in the heap


during execution, dynamic variables scope is controlled by the
programmer.

Video lecture: Pointers


https://youtu.be/4UED3iLxfoY

©Saif Bashar 2019


CHAPTER 09 Saif.io

9.2 Pointers as Function’s Argument

We learned in Chapter 5 that we can pass parameters to a


function either by value or by reference or by pointer, and in order to
pass by pointer we needed pointers to store the variable’s reference
or address.

Sending parameters by pointer make our programs run faster,


because we only pass the address not the whole data, this is
become very useful in passing large data. Important feature of
sending data by pointer or by reference is the change on the data
inside the function will be reflected in all the program because when
we pass the data’s reference we are working on the original data,
while when we pass data by value we are working on a copy of the
data.

Video lecture: Pointers with Function Arguments


https://youtu.be/mSfgFhSQUos

9.3 Pointers with Arrays


We can use pointers to reach array elements, as we know that
array’s elements are adjacent in memory, so if we declare a pointer
and assign to it the address of the first element of the array, we can
easily navigate to the other elements by incrementing this pointer,
the following code will print the array’s elements using a pointer:

int a[3]={10,20,30};
int *ptr;
ptr = a;
cout<<*ptr<<endl;
cout<<*(++ptr)<<endl;
cout<<*(++ptr)<<endl;

©Saif Bashar 2019


CHAPTER 09 Saif.io

Since the array’s name represent the address of the first element
then we don’t need to use the reference operator with arrays.

The following function represent copying a string using pointers:


void copy(char *dest, char *src){
while(*dest++ = * src++);
}

Video lecture: Pointers with Arrays


https://youtu.be/_bEdxOGuPSU

9.4 Pointers with Structures


We can declare pointer to a structure this is very useful
especially with structures of large size, declaring a regular structure
above the main function:

struct student{
long id;
string name;
int age;
string address;
float mark1;
float mark2;
float mark3;
};

©Saif Bashar 2019


CHAPTER 09 Saif.io

Inside the main function creating a pointer to an instance of the


student structure:

student *noor;
noor->id = 1;
noor->name = "noor";
noor->age = 20;
noor->address = "Baghdad";
noor->mark1 = 85.6;
noor->mark2 = 83.6;
noor->mark3 = 88.4;

We use the arrow operator -> instead of the dot operator to access
the members of the instance when we work with pointers.

Video lecture: Pointers with Structures


https://youtu.be/wttfnaMA5cY

©Saif Bashar 2019


CHAPTER 09 Saif.io

Exercises 9
Q1: Write a program that apply mathematical pointer operations
Video lecture: Solution for Q1 - Exercises 9
https://youtu.be/L1huH24P-l0

Q2: Find the output for the following code segment:


int *x;
int *p,*q;
int c=100,a;

x=&c;
p=x+2;
q=x-2;
a=p-q;

cout<<x;
cout<<p;
cout<<q;
cout<<a;

Video lecture: Solution for Q2 - Exercises 9


https://youtu.be/sfgOvcpY3qo

©Saif Bashar 2019


Chapter 10
Files
10.1 Introduction
10.2 Open, Write & Close
10.3 Open, Read & Close
10.4 Using the fstream Library
Exercises 10

s a i f . i o
CHAPTER 10 Saif.io

10.1 Introduction
The programs that we wrote in the previous chapter lost their
data as soon as the program finish its execution, because we were
working with variables, arrays or structures all stored in memory and
when the program finish its execution it will be unloaded from
memory and all our data is lost.

What if we wanted to store our data in a permanent storage like the


hard disk, we can do that using files, C/C++ provide many ways
methods to let us work with files, some are built-in inside the
language standard library and some methods by using additional
libraries like the fstream library we will discuss both methods in this
chapter.

All programming languages provide functions that deals with files


these functions are usually:

- Open file in a specified path


- Write to a file
- Read from a file
- Close file
- Remove file

The next paragraphs will discuss the built-in C/C++ functions that
perform the above operations on files.

©Saif Bashar 2019


CHAPTER 10 Saif.io

10.2 Open, Write & Close


Before we can use the available functions, we have to declare
a pointer that will point to the file that we will work with, this is can be
done using a pointer of type file with the keyword FILE

FILE *myfile;

We can open a file using the function fopen()this function takes two
arguments the first one is to specify the file’s path as a string and the
second argument is to specify the mode as a string.

The mode can take the following values:

- "w" for opening a file to write data into


- "a" for opening a file to append data to it
- "r" for opening a file to read data from

So, for opening a file for writing named 1.txt inside our project
directory the code will be:

myfile = fopen("1.txt", "w");

Now the file is created and ready for writing data, we use the
function putc() to write characters in our file this function takes two
arguments the first one is the character we want to store in the file
and the second argument is the file pointer that we declared.

char ch=’A’;
putc(ch, myfile);

after we finish writing data to the file we need to close the file by
using the fclose() function which takes one argument the file
pointer.

fclose(myfile);

©Saif Bashar 2019


CHAPTER 10 Saif.io

We can also use loops to store as many characters we want, for


example the following program will keep reading characters and
write them to the file and stop when the user enters the x character.

Program 10.1
1 // opening a file for writing
2 #include<iostream>
3 using namespace std;
4
5 int main () {
6
7 FILE *myfile;
8 char path[] = "1.txt";
9 char ch;
10
11 myfile = fopen(path, "w");
12
13 do{
14 cin.get(ch);
15 if(ch!=’x’)
16 putc(ch, myfile);
17 }while(ch!=’x’);
18
19 fclose(myfile);
20
21 return 0; }

Note that I used the cin.get() function to read characters because


this function also reads the new line characters while cin ignore the
new line character.

Opening an existing file with the writing mode will create a new
empty file, if we have a file that contain data and we want the add
data to it we have to use the append mode.

myfile = fopen("1.txt", "a");

©Saif Bashar 2019


CHAPTER 10 Saif.io

10.3 Open, Read & Close


We can also open files to read data from, this means the file
already contains data and we open it and enter a loop to keep
reading its characters. But how we know when to terminate the loop
in other words what will specify the end of the file? Remember in
Chapter 7 we talked about strings and we saw that there is a special
character that terminate a string which is the null character /0, in files
we have another special character that specify the file’s end which
is EOF so the loop for reading characters form the file will keep
reading characters until it reaches the EOF and stops.

The function that reads data from files is getc() and it take one
argument as the file pointer and returns a character

ch = getc(myfile);

The following program demonstrate the read from file code:

Program 10.2
1 // opening a file for reading
2 #include<iostream>
3 using namespace std;
4 int main () {
5 FILE *myfile;
6 char path[] = "1.txt"; //file should exist
7 char ch;
8
9 myfile = fopen(path, "r");
10
11 while((ch= getc(myfile))!=EOF){
12 cout<<ch;
13 };
14
15 fclose(myfile);
16
17 return 0;
18 }

©Saif Bashar 2019


CHAPTER 10 Saif.io

10.4 Using the fstream Library


The second method working with files is by using the fstream
library take the files we create as an input stream and other files as
an output stream. Remember when we used the iostream library
the default input stream was from the keyboard and the default
output stream was the screen, so to work with files we have to add
this line to include the fstream library:

#include <fstream>

The fstream library provides several functions that let us work with
files, there is a function that open a file, and a function that close a
file, the fstream library have two streams one is for input which is the
ifstream that is used when we want to open an existing file to read
data from. And there is the ofstream that is used when we want to
open a file to write data to.

So, if we have a text file in the same directory of our program called
1.txt that contains a string, so in order to open it we need to use the
ifstream with the extraction operator >> to read the data and
store it in appropriate variable. See Program 10.3 that open a file
and read its data and print it to the screen.

©Saif Bashar 2019


CHAPTER 10 Saif.io

Program 10.3
1 // opening a file for reading
2 #include<iostream>
3 #include<fstream>
4 using namespace std;
5
6 int main () {
7 ifstream file;
8 string filename = "1.txt";
9 string input;
10
11 file.open(filename);
12 file>>input;
13 file.close();
14
15 cout<<input;
16 return 0; }

Line 7 declare a variable of type ifstream for files to read from,


Line 8 declares a string that will hold the file path that we want to
open.

Line 11 use the open function provided by the ifstream and it take
one argument as a string that represent the file path.

The file now is open and ready to read form by using the extraction
operator and store the data read from the file in the string variable
input, Line 12.

Line 13 used the function close to close the opened file.

©Saif Bashar 2019


CHAPTER 10 Saif.io

We can also open a file to write data to it by using the ofstream


with the insertion operator >>, see the following program:

Program 10.4
1 // opening a file for writting
2 #include<iostream>
3 #include<fstream>
4 using namespace std;
5
6 int main () {
7 ofstream file;
8 string filename = "out.txt";
9 string data = "this is a test";
10
11 file.open(filename);
12 file<<data;
13 file.close();
14
15 return 0;
16 }

Line 7 declare a variable of type ofstream for files to write data to,
Line 8 declares a string that will hold the file path that we want to
open.

Line 11 use the open function provided by the ofstream and it take
one argument as a string that represent the file path.

The file now is created and ready to write to by using the insertion
operator and store the data in the string variable data, Line 12.

Line 13 used the function close to close the opened file.

After running this program, you can check the file out.txt in your
program folder to see its content.

©Saif Bashar 2019


CHAPTER 10 Saif.io

Note that we can read or write to a file in a path in the computer, for
example if we want to write to a file named out.txt in hard disk in
partition D in a folder named archive the code can be like this:

string filename = "D:\\archive\\out.txt";


file.open(filename);

The double backslash is an escape sequence to produce only one


backslash.

©Saif Bashar 2019


CHAPTER 10 Saif.io

Exercises 10
Q1: Write a program that backup a text file named article.txt into a
folder named backup that should contain a file named
articleBackup.txt
Video lecture: Solution for Q1 - Exercises 10
https://youtu.be/L1huH24P-l0

©Saif Bashar 2019


Chapter 11
Classes & Objects
11.1 Overview on OOP
11.2 Defining a Class
11.3 Constructors
11.4 Constructor Overloading
11.5 Destructors
11.6 Scope Resolution Operator
11.7 Constant & Static Members
Exercises 11

Part 2
s a i f . i o
CHAPTER 11 Saif.io

11.1 Overview on OOP


This part of the book is dedicated to the Object-oriented features
that were added to the original C language by Bjarne Stroustrup, in order
to understand this chapter and the following chapters you must have a
solid understanding on all the chapters discussed in part one, you have to
gain mastery on all the fundamental concepts and control structures of
the C language like conditions, loops, functions, arrays, strings, structures
and pointers and all the details explained earlier.

So, what is OOP? first of all OOP is not a programming language, it is a style
of programming that is applied to many programming languages, this
mean that C++ is not the only object-oriented language in a matter of fact
the first object oriented language was a language called Simula and what
Bjarne did is that he applied the OOP features to the original C language
and called the new version C with classes then the name changed to
C++.

The old style of programming that we learned in the previous chapters


called procedural programming, the program was consisting of a number
of functions (procedures) that perform a specific task, and a main function
that control the program execution, in OOP style of programming we have
classes and objects, a class is a general term like the term Bird and a
specific dove is an object created from the bird class, a sparrow is another
object that we can create from the bird class, we cannot create a cat
object from the bird class because it’s simply doesn’t make sense, we
should make a class for cats to create cat objects, so objects belonging to
a class share common attributes and functionalities, attributes also called
data members, functions that belong to a class are called member
functions or methods.

We create objects from classes, objects have attributes (data) and


methods
Object = Attributes + Methods

©Saif Bashar 2019


CHAPTER 11 Saif.io

Let me give you another example, the football player can be considered
a class and the individual players are objects created from that class.
Football players all share common attributes all of them have speed,
length, skills, position, shoot strength ...etc. but each individual player has
his own values, and all of them have functionalities they all run, pass, shot
some of them attack some of them defend …etc.

Figure 11.1 Football Player Class and it’s Objects

I’m sorry that Ronaldo moved to Juventus and ruined this example for me.
But you get the idea.

Anything in the world can be an object, an object is a specific item that


belong to a class, it also called an instance of a class.

Classes and objects are similar to structures in C language (discussed in


Chapter 8) we create objects from the class similar to what we did with
structures when we created structure instances form it, the difference
between a structure and a class is structures members are public while

©Saif Bashar 2019


CHAPTER 11 Saif.io

class members are private by default, plus all the features of OOP that we
will study are provided for the classes and objects.

So, why we need to program in the OOP style? The invention of this style of
programming came to solve issues and problems that appeared in the old
style of programming especially with large programs, programmers
needed a way to protect their data from the rest of the program they
needed a cleaner way to organize the code in classes that hold objects
with common attributes and functionalities, this isolation of data or data
hiding or encapsulation provided a layer of protection to the data. Classes
also provide data abstraction which is the process of paying attention to
important properties while ignoring the details of implementation, when
you as a programmer don’t need to know the details of a specific class
you just want to benefit from its functionality all the implementation details
are hidden inside the class. A class is like a capsule that contains data and
methods.

Also, this grouping of code made error handling easier since the code of
each class in isolated from the other classes in the program.

Another powerful feature of OOP is inheritance which is simply means


inherit the code that was previously written rather than write it all over
again, this will save development time and make C++ programmers more
productive, another feature is polymorphism which means a specific
function can take many forms, the modules will change the way they
operate depending on the context as we will see later. And other many
new exiting features added to the programming languages to make
programming more productive, safer, and easier to handle errors.
Anywhere you go now (web development, mobile apps, desktop
programs … etc.), any famous language you pick you will see the features
of OOP are supported and heavily used, we will study these features in
details in the upcoming chapters.

©Saif Bashar 2019


CHAPTER 11 Saif.io

To summarize, OOP support all the procedural programming features and


also provide:

- Data abstraction
- Encapsulation (data hiding)
- Inheritance (reusability)
- Operator overloading
- Polymorphism
- Exception handling

Encapsulation, inheritance and polymorphism are considered the pillars of


OOP paradigm

Figure 11.2 Pillars of OOP

©Saif Bashar 2019


CHAPTER 11 Saif.io

11.2 Defining a class


Class definition depends on our understanding to the problem we
want to solve, we have to think about what attributes or data we need to
put in the class then what methods are needed to process that data, the
syntax of defining a class in C++.

Defining a Class

class className {

private:
data1;
function1(){}

public:
data2;
function2(){}

protected:
data3;
function3(){}
};

The class definition will contain attributes or data and methods, with three
access specifiers: private, public and protected

private: mean the data are private and can be accessed only from
inside the class and some friends (more about friends in Chapter 12), note
that this is the default access specifier for classes, I mean if you don’t write
an access specifier it will be considered private to ensure the
encapsulation of data.

©Saif Bashar 2019


CHAPTER 11 Saif.io

public: the data and methods are public and can be accessed from
anywhere in the program, usually methods are specified public so we can
call them from the main function, this section is also called the class
interface.

protected: I will explain it in Chapter 15 when we will talk about


inheritance.

So, for example if we want to find the area and circumference of any
rectangle in the OOP style, first of all we need to think about what should
we name the class, well in this case it’s obvious let us call it rectangle, then
we need to think what attributes or data this class will hold, as long as our
problem is to find the area and the circumference so we need the
dimensions width and length, so we can write the definition of the class as
follows: (this definition will go above the main function)

class rectangle {
private:
int width, length;
};

Then we need to think about the methods, it is also obvious we need to


calculate the area and the circumference so we need two methods for
now, our definition will be after adding the two methods:

class rectangle {
private:
int width, length;

public:
int area(){
return width * length;
}

int circumference(){
return (width + length)*2;
} };

©Saif Bashar 2019


CHAPTER 11 Saif.io

Note that the methods are added in the public section so we can call
them from anywhere, and the data are in the private section to ensure
encapsulation.

After completing the class definition, we need to create objects from this
class, remember that the rectangle class will represent every rectangle in
the world, there are infinite number of rectangles.

We declare objects anywhere in the program, lets declare an object in


the main function

int main (){


rectangle r1, r2;

return 0;
}

Note that we declared two objects r1 and r2, they represent two
rectangles, but now we have a problem, how we supposed to give the
dimensions of each rectangle?

If we do this:

class rectangle {
private:
int width=5, length=9;

public:
int area(){
return width * length;
}

int circumference(){
return (width + length)*2;
}

};

©Saif Bashar 2019


CHAPTER 11 Saif.io

This will make all our rectangle objects have the same dimensions which is
clearly wrong.

We can’t do this also

int main (){


rectangle r1, r2;
r1.width = 5;
r1.length = 9;

r2.width = 2;
r2.length = 6;

return 0;
}

We will get an error for this because width and length are private, we
cannot access them from anywhere outside the class even from the main
function.

We can make width and length public though but we will break the
encapsulation paradigm.

The accepted solution for this problem i.e. initializing the data members of
a class is to create a member function with this task, the function will be
public and it will receive the values passed to it then assign these values to
the data members of the class, the following program create a member
function called setValues() that will initialize the data members for each
object.

©Saif Bashar 2019


CHAPTER 11 Saif.io

Note we call class members using the (dot) the member access operator
like we used to do with structures. So, our rectangle program can be
written like this:

Program 11.1
1 // Building a class & working with objects
2 #include<iostream>
3 using namespace std;
4 class rectangle {
5 private:
6 int width, length;
7 public:
8 void setValues(int x, int y){
9 width = x;
10 length = y; }
11
12 int area(){
13 return width * length; }
14
15 int circumference(){
16 return (width + length)*2; }
17 };
18 int main () {
19 rectangle r1,r2;
20
21 r1.setValues(5,9);
22 r2.setValues(2,6);
23
24 cout<<"r1 area is: "<<r1.area()<<endl;
25 cout<<"r2 area is: "<<r2.area()<<endl;
26 cout<<"r1 crcumference is: "
27 <<r1.circumference()<<endl;
28 cout<<"r2 crcumference is: "
29 <<r2.circumference()<<endl;
30 return 0;
32 }

Video lecture: OOP Introduction


https://youtu.be/i4SN8XFVpTk

©Saif Bashar 2019


CHAPTER 11 Saif.io

11.3 Constructors
There is a better way to initialize the class data members by using a
special function called a constructor, the class constructor has these jobs:

- Initialize the class data members


- Reserve memory space for the object depending on its contents

A constructor has the following properties:

- It has the same name of the class


- It has no return type
- Called automatically when the object is declared
- Can be overloaded

Since the constructor is called automatically then we don’t have to call it


like we did with the setValues() function in Program 11.1, adding a
constructor to our previous program see Program 11.2

The setValues() function was replaced by the class constructor on Line 8,


see that the constructor has exactly the same name of the class, and it has
no return type, and it initialize the class data.

The main function has the declaration of two objects, note that we send
the initial values for each object in the object declaration statement on
Line 19, since the constructors will be called automatically we don’t have
to call them in code like we did in the setValues() function see Program
11.1 Line 21 and Line 22.

©Saif Bashar 2019


CHAPTER 11 Saif.io

Program 11.2
1 // Adding a constructor
2 #include<iostream>
3 using namespace std;
4 class rectangle {
5 private:
6 int width, length;
7 public:
8 rectangle(int x, int y){
9 width = x;
10 length = y; }
11
12 int area(){
13 return width * length; }
14
15 int circumference(){
16 return (width + length)*2; }
17 };
18 int main () {
19 rectangle r1(5,9),r2(2,6);
20
21 cout<<"r1 area is: "<<r1.area()<<endl;
22 cout<<"r2 area is: "<<r2.area()<<endl;
23 cout<<"r1 crcumference is: "
24 <<r1.circumference()<<endl;
25 cout<<"r2 crcumference is: "
26 <<r2.circumference()<<endl;
27 return 0;
28 }

We can also write the constructor like this:


rectangle(int x, int y): width (x), length (y){ }

This syntax is called member initialization list

©Saif Bashar 2019


CHAPTER 11 Saif.io

11.4 Constructor Overloading


The overloading concept in programming means assign more than
one job, we have seen function overloading in Chapter 5, function
overloading means multiple implementations for the same function, the
correct function is called depending on number or type of the arguments
it receives. A class constructor is also a function and it can be overloaded,
see the following program:

Program 11.3
1 // constructor overloading
2 #include<iostream>
3 using namespace std;
4 class rectangle {
5 private:
6 int width, length;
7 public:
8 rectangle(){
9 cout<<"Enter Dimensions: ";
10 cin>>width>>length; }
11
12 rectangle(int x, int y){
13 width = x;
14 length = y; }
15
16 int area(){
17 return width * length; }
18
19 int circumference(){
20 return (width + length)*2; }
21 };
22 int main () {
23 rectangle r1;
24 rectangle r2(2,6);
25 cout<<"r1 area is: "<<r1.area()<<endl;
26 cout<<"r2 area is: "<<r2.area()<<endl;
27 cout<<"r1 crcumference is: "
28 <<r1.circumference()<<endl;
29 cout<<"r2 crcumference is: "
30 <<r2.circumference()<<endl;
31 return 0; }

©Saif Bashar 2019


CHAPTER 11 Saif.io

Note that the class in Program 11.3 have two constructors, the first one
receives no parameters because it reads the rectangle dimensions, the
other constructor receives two values and assign them to the class data.

The first constructor will be called automatically when the object r1 is


declared in Line 23, the second constructor will be called automatically
when object r2 is declares in Line 24.

We can add as many constructors as we want in the class definition, but


remember that an object will call only one constructor at runtime.

Video lecture: Constructor Overloading


https://youtu.be/MQsjwSxMbD4

11.5 Destructors
The other special function that can be added to the class definition is
the destructor. The destructor job is the opposite of constructor, it destructs
the object to free the memory occupied by it.

Destructor job is:

- Remove the object and free up the memory that was reserved for it.

A destructor has the following properties:

- It has the same name of the class


- The name begins with tilde ~
- It has no return type
- It has no arguments
- Called automatically at the end of the object’s scope, or when we
delete the whole object
- Cannot be overloaded

©Saif Bashar 2019


CHAPTER 11 Saif.io

So, the destructor job is to remove the object from memory, by removing
the object we need to delete its data, but we cannot delete variables
since they represent fixed memory locations, so we have to work with
pointers, we can delete a pointer by making it point to something else so
the location it was pointing to will be freed and returned to the operating
system.

We delete pointers by using the delete operator, but to use the delete
operator we have to create the pointer using the new operator, as a
dynamic variable created it in the heap.

So, our class definition will initialize the data in the constructor using the new
operator then delete the data using the delete operator in the destructor,
see Program 11.4

When we work with OOP and want to build a complete class we have to
think about these things:

Figure 11.3 A Complete Class

Video lecture: Constructor & Destructor


https://youtu.be/8xYuJ94MVo4

©Saif Bashar 2019


CHAPTER 11 Saif.io

Program 11.4
1 // Adding a destructor
2 #include<iostream>
3 using namespace std;
4 class rectangle {
5 private:
6 int *width, *length;
7 public:
8 rectangle(int x, int y){
9 width = new int;
10 length = new int;
11 *width = x;
12 *length = y; }
13
14 ~rectangle(){
15 delete width;
16 delete length; }
17
18 int area(){
19 return *width * *length; }
20
21 int circumference(){
22 return (*width + *length)*2; }
23 };
24 int main () {
25 rectangle r1(5,9),r2(2,6);
26
27 cout<<"r1 area is: "<<r1.area()<<endl;
28 cout<<"r2 area is: "<<r2.area()<<endl;
29 cout<<"r1 crcumference is: "
30 <<r1.circumference()<<endl;
31 cout<<"r2 crcumference is: "
32 <<r2.circumference()<<endl;
33 return 0;
34 }

©Saif Bashar 2019


CHAPTER 11 Saif.io

11.6 Scope Resolution Operator


We can sperate the class definition from the implementation of the
class member functions. I mean we can write the member functions of the
class outside the class by using a special operator called the scope
resolution operator written like this :: as two adjacent colons, the syntax
for using the scope resolution operator:

Scope resolution operator

returnType className::funcName (){


}

Also, we need to leave the function prototype inside the class. Let us take
the functions of the class in Program 11.2 outside the class definition, take
a look at the following program:

Program 11.5
1 // Scope resolution operator
2 #include<iostream>
3 using namespace std;
4 class rectangle {
5 private:
6 int width, length;
7 public:
8 rectangle(int, int);
9 int area();
10 int circumference();
11 };
12 rectangle::rectangle(int x, int y){
13 width = x;
14 length = y; }
15
16 int rectangle::area(){
17 return width * length; }
18
19 int rectangle::circumference(){
20 return (width + length)*2; }

©Saif Bashar 2019


CHAPTER 11 Saif.io

Note that we took out the constructor, the area and the circumference
member function outside the class by using the scope resolution operator,
and we left their prototypes inside the class.

The reason behind implementing the member functions outside the class is
that in the case the class contains large number of functions it become
hard to read and understand, taking out the member functions, make the
class definition more condense and easier to read for the programmer.

Always remember the main six steps of building a complete class in C++

Costructor Methods
Data
Members
Destructor

Object Class Implementation

Figure 11.4 Steps of Building a class in C++

11.7 Constant & Static Members


We can use constant data members in the class definition, as you
may recall we talked about constant variables in Chapter 2, we’ve seen
that a constant variable means a variable that its value cannot be
change.

We use the keyword const to declare constants and we know that


constants must be initialized when declared, in classes when we declare a
data member as constant we have to use with it the member initialization
list method, see Program 11.6 that define a circle class with PI as constant
data member.

©Saif Bashar 2019


CHAPTER 11 Saif.io

Line 9 the constructor receives two values the integer r assigned to the
radius data member and the pi assigned to the PI data member using the
member initialization list syntax because it’s a constant.

Program 11.6
1 // Constant data member
2 #include<iostream>
3 using namespace std;
4 class circle {
5 private:
6 int radius;
7 const float PI;
8 public:
9
10 static int total;
11
12 circle(int r):PI(3.14){
13 radius = r;
14 total++;
15 }
16
17 int area(){
18 return radius * radius * PI; }
19 };
20
21 int circle::total=0;
22
23 int main () {
24 circle c1(7), c2(4);
25 cout<<"c1 area is: "<<c1.area()<<endl;
26 cout<<"c2 area is: "<<c2.area()<<endl;
27 cout<<"you have "<<circle::total<<" circles";
28 return 0; }

We can set function’s arguments as constants to protect them from


altering, further more we can define constant objects with fixed values.

©Saif Bashar 2019


CHAPTER 11 Saif.io

We can also have static data members declared inside the class; a static
variable is created only once in the program so if we have multiple objects
they will share the static member. We can count the number of objects
created using static data members, or the number of functions calls and
other useful purposes.

Static data members are initialized outside the class using the scope
resolution operator.

Video lecture: Constant & Static Members


https://youtu.be/3YAaeP9KfuI

11.8 Constant Objects


We can create objects as constant so we cannot change their data,
for example if we have a class Date we can define its object as constant

const Date birthday(10, 10, 1990);

Note that only constructor and destructor will be able to modify the
object, any other member function is not allowed to do so. Only constant
methods can be called from a constant object, like the following method
of class Date

int Date::getMonth() const{

return month;

Objects that are not constant can call constant member functions and
non-constant member functions.

©Saif Bashar 2019


CHAPTER 11 Saif.io

Exercises 11
Q1: Write an object-oriented program in C++ that represent a simple
arithmetic calculator
Video lecture: Solution for Q1 - Exercises 11
https://youtu.be/VWLFiLXw_fM

©Saif Bashar 2019


Chapter 12
Friends
12.1 Friend Function
12.2 Friend Class
Exercises 12

s a i f . i o
CHAPTER 12 Saif.io

12.1 Friend Function


We established in the previous chapter that the data members
of a class should remain private, and by private access specifier
we make the data accessible only for member functions of the class
whether those functions were inside the class or implemented
outside the class using the scope resolution operator.

There is a special function that can access private data of a class,


this function is called friend function. Friend functions are regular
functions that does not belong to the class, yet they can access the
class’s private data.

Implementing a friend function, require all the parts necessary to


build a regular function plus keep in mind these two points:

- Use the keyword friend in the function’s prototype inside


the class definition
- Friend functions receive objects as arguments, in order to
access the object’s private data

Let’s define a student class that contain the following data


members:
- ID
- Name
- Age
- Deg1
- Deg2
- Deg3

Then implement a friend function that calculate the students


average, check out Program 12.1

©Saif Bashar 2019


CHAPTER 12 Saif.io

Program 12.1
1 // friend function
2 #include<iostream>
3 using namespace std;
4 class student {
5 private:
6 string Name;
7 int ID, Age, Deg1, Deg2, Deg3;
8 public:
9 student(int id, string n, int a, int d1, int
10 d2, int d3){
11 ID=id;
12 Name=n;
13 Age=a;
14 Deg1=d1;
15 Deg2=d2;
16 Deg3=d3;
17 }
18 friend float average(student&);
19 };
20
21 float average(student &s){
22 float avg=(float)(s.Deg1+s.Deg2+s.Deg3)/3.0;
23 return avg;
24 }
25
26 int main(){
27 student s1(1003, "Mariam", 20, 76, 78, 98);
28 cout<<average(s1);
29 return 0;
30 }

Note that the average () function implemented outside the class as


a regular function without using the scope resolution operator, but in
order for it to be a friend function for the student class its prototype is
added inside the class with the friend keyword Line 18.

Also note that the friend function received an object as an


argument in order to access the student’s degrees.

©Saif Bashar 2019


CHAPTER 12 Saif.io

Friend functions are useful when we want them to process data for
many objects belong to the same class or different classes.

Let’s define an employee class that contain the following data


members:
- Name
- Age
- Salary
- City

Use a friend function that find the summation of salaries of three


employees

So, we will create the class with the data members above then
create a constructor, and define three objects in the main function.

We will send these three objects by reference to a friend function


sum() that will access the salary of each employee and return the
summation value.

Checkout Program 12.2

Video lecture: Friend Function


https://youtu.be/7YHg7ZNLNd8

©Saif Bashar 2019


CHAPTER 12 Saif.io

Program 12.2
1 // friend function for multiple objects
2 #include<iostream>
3 using namespace std;
4 class emp {
5 private:
6 string Name, City;
7 int Age, Salary;
8 public:
9 emp(string n, int a, int sal, string c){
10 Name=n;
11 Age=a;
12 Salary=sal;
13 City=c;
14 }
15 friend int sum(emp&, emp&, emp&);
16 };
17
18 int sum(emp &e1, emp &e2, emp &e3){
19 int s=e1.Salary+ e2.Salary + e3.Salary;
20 return s;
21 }
22
23 int main(){
24 emp e1("Mustafa", 42, 1500, "Baghdad");
25 emp e2("Ahmed", 39, 2500, "Babel");
26 emp e3("Muhanned", 40, 1200, "kut");
27 cout<<sum(e1,e2,e3);
28 return 0;
29 }

©Saif Bashar 2019


CHAPTER 12 Saif.io

12.2 Friend Class


When we have several friend functions we can group them
inside a class lets name it class B, and make class B a friend to other
class let’s call it class A, so we will need only to mention inside class A
the prototype of the friend class B. And all its member functions will
be considered friend functions to class A. you don’t have to put the
functions prototypes inside class A.

Steps of making class B friend to class A


- Put the class B declaration inside class A with the friend
keyword
- When calling a member function of class B, pass to it an
object from class A

Let us take a serious example that represent two classes that


represent two banks namely AlRafidain and AlRasheed banks.
Suppose a client of AlRasheed bank wants to transfer money from
AlRashed bank to AlRafidain bank, let’s make AlRasheed class a
friend to the AlRafidain bank.

Video lecture: Friend Class


https://youtu.be/jwcpnA32lyc

The following example illustrate two bank classes the second class is
a friend to the first class.

©Saif Bashar 2019


CHAPTER 12 Saif.io

Program 12.3
1 // friend class for banks
2 #include<iostream>
3 using namespace std;
4 class AlRafidain {
5 private:
6 string Name;
7 int balance;
8 public:
9 AlRafidain(string n, int b){
10 Name=n;
11 balance=b; }
12
13 float getBalance(){
14 return balance;
15 }
16
17 void deposite(float amount){
18 balance+=amount;
19 }
20
21 void withdraw(float amount){
22 balance-=amount;
23 }
24
25 friend class AlRashid;
26 }; //end of AlRafidain class
27
28 class AlRashid{
29 private:
30 string Name;
31 int balance;
32 public:
33 AlRashid(string n, int b){
34 Name=n;
35 balance=b; }
36
37 float getBalance(){
38 return balance;
39 }
40
41 void deposite(float amount){
42 balance+=amount; }

©Saif Bashar 2019


CHAPTER 12 Saif.io

Program 12.3 cont.


43 void withdraw(float amount){
44 balance-=amount;
45 }
46
47 void transfer(AlRafidain& Client){
48 int amount;
49 cout<<"How much to transfer?: ";
50 cin>>amount;
51 if(amount<=Client. getBalance())
52 { balance+= amount;
53 Client.balance -= amount; }
54 else
55 cout<<"Not enough balance"<<endl;
56 }
57 }; //end of AlRashid class
58
59 int main(){
60 AlRafidain ahmed("Ahmed", 1000);
61 ahmed.deposite(500);
62 cout<<"Ahmed balance : ";
63 cout<<ahmed.getBalance()<<"$"<<endl;
64
65 ahmed.withdraw(700);
66 cout<<"Ahmed balance now : ";
67 cout<<ahmed.getBalance()<<"$"<<endl;
68
69 AlRashid ali("Ali", 500);
70 cout<<"Ali balance : ";
71 cout<<ali.getBalance ()<<"$"<<endl;
72
73 ali.transfer(ahmed);
74
75 cout<<"Ali balance : ";
76 cout<<ali.getBalance()<<"$"<<endl;
77
78 cout<<"Ahmed balance : ";
79 cout<<ahmed.getBalance()<<"$"<<endl;
80
81 return 0; }

©Saif Bashar 2019


CHAPTER 12 Saif.io

Exercises 12

Q1: Write an object-oriented program in C++ that represent a car,


the class constructor will set the values to all its data members,
create a member function outside the class to display the car price,
then create a friend function to increase the car price by 1000

Video lecture: Solution for Q1 - Exercises 12


https://youtu.be/SvZqPijZhHk

Q2: Write an object-oriented program in C++ that represent the


student, the class constructor will set the values to all its data
members, create another class to represent the university, use a
member function of the second class to print the values of the first
class

Video lecture: Solution for Q2 - Exercises 12


https://youtu.be/zajf197KQP8

©Saif Bashar 2019


Chapter 13
Pointers & Arrays of
Objects
13.1 Array of Objects
13.2 Implicit Member Argument
13.3 Pointer to Object
13.4 Class Object Member
Exercises 13

s a i f . i o
CHAPTER 13 Saif.io

13.1 Array of Objects


As we studied in Chapter 5, arrays can represent multiple
elements of the same type, we worked with arrays of integers, arrays
of floats, arrays of characters, arrays of strings and arrays of
structures, now we will work with array of objects.

We can declare three or four objects in the main function, but when
we have 100 object it is more efficient to declare an array of objects
of size 100, the syntax is the same as array of structures.

As we always use loops in working with arrays we can also send the
whole array of objects to friend functions

Rewriting Program 12.1 using array of objects for 20 students

Note that in Line 34 a declaration of an array of size 20 this mean it


will hold 20 objects of the class student, the important thing is that this
declaration will invoke the constructor 20 times, a constructor for
each object created, the constructor invoked will read the data
from the user

student s[SIZE];

if the constructor was supposed to receive data from the main


function, the array of object declaration should be like this. (if SIZE
was 5)

student s[SIZE]={student(1,"Ali",20,56,78,98),
student(2,"Ahmed",21,57,88,38),
student(3,"Noor",21,57,80,56),
student(4,"Sara",21,87,88,65),
student(5,"Zahraa",21,70,82,81),
};

©Saif Bashar 2019


CHAPTER 13 Saif.io

Program 13.1
1 // Array of Objects
2 #include<iostream>
3 #define SIZE 20
4 using namespace std;
5 class student {
6 private:
7 string Name;
8 int ID, Age, Deg1, Deg2, Deg3;
9 public:
10 static int counter;
11 student(){
12 cout<<"Object Number "<<counter<<endl;
13 cout<<"Enter student ID: "; cin>>ID;
14 cout<<"Enter student Name: "; cin>>Name;
15 cout<<"Enter student Age: "; cin>>Age;
16 cout<<"Enter student Deg1: "; cin>>Deg1;
17 cout<<"Enter student Deg2: "; cin>>Deg2;
18 cout<<"Enter student Deg3: "; cin>>Deg3;
19 counter++;
20 }
21
22 string getName(){
23 return Name;
24 }
25
26 float average(){
27 return (Deg1 + Deg2 + Deg3)/3.0;
28 }
29 };
30
31 int student::counter=1;
32
33 int main(){
34 student s[SIZE];
35
36 for(int i=0; i<SIZE; i++)
37 cout<<s[i].getName()<<" Average "
38 <<s[i].average()<<endl;
39
40 return 0;
41 }

©Saif Bashar 2019


CHAPTER 13 Saif.io

13.2 Implicit Member Argument


When a class member function is called there is an implicit
argument passed to it, this argument represents the object itself we
can refer to this object using this keyword.

this represent a pointer that points on the current object, since it’s a
pointer to object we have to use the arrow operator -> to access the
object’s members.

Rewriting Program 11.2 using this pointer

Program 13.2
1 // using this pointer
2 #include<iostream>
3 using namespace std;
4 class rectangle {
5 private:
6 int width, length;
7 public:
8 rectangle(int width, int length){
9 this->width = width;
10 this->length = length; }
11
12 int area(){
13 return width * length; }
14
15 int circumference(){
16 return (width + length)*2; }
17 };
18 int main () {
19 rectangle r1(5,9),r2(2,6);
20
21 cout<<"r1 area is: "<<r1.area()<<endl;
22 cout<<"r2 area is: "<<r2.area()<<endl;
23 cout<<"r1 crcumference is: "
24 <<r1.circumference()<<endl;
25 cout<<"r2 crcumference is: "
26 <<r2.circumference()<<endl;
27 return 0;
28 }

©Saif Bashar 2019


CHAPTER 13 Saif.io

13.3 Pointer to Object


We can create pointers to objects in our programs and use the
arrow operator to access the object’s member, its more efficient to
use pointers to objects and it give the programmer the control over
the objects scope.

We declare a pointer to object like the following code (refer to


Program 13.2)

rectangle *r1, *r2;

After declaring the pointers, we have to resrve a place in memory for


them using the new operator like the following syntax:

r1 = new rectangle(5,9);
r2 = new rectangle(2,6);

when we finish working with these objects we can delete them using
the delete operator

delete r1;
delete r2;

Using the delete operator will call the object destructor to free the
memory occupied by the object.

Program 13.2 can be rewritten using pointer to object, see Program


13.3

©Saif Bashar 2019


CHAPTER 13 Saif.io

Program 13.3
1 // pointer to object
2 #include<iostream>
3 using namespace std;
4 class rectangle {
5 private:
6 int width, length;
7 public:
8 rectangle(int width, int length){
9 this->width = width;
10 this->length = length; }
11
12 int area(){
13 return width * length; }
14
15 int circumference(){
16 return (width + length)*2; }
17 };
18 int main () {
19 rectangle *r1,*r2;
20 r1 = new rectangle(5,9);
21 r2 = new rectangle(2,6);
22
23 cout<<"r1 area is: "<<r1->area()<<endl;
24 cout<<"r2 area is: "<<r2->area()<<endl;
25 cout<<"r1 crcumference is: "
26 <<r1->circumference()<<endl;
27 cout<<"r2 crcumference is: "
28 <<r2->circumference()<<endl;
29
30 delete r1;
31 delete r2;
32
33 return 0;
34 }

©Saif Bashar 2019


CHAPTER 13 Saif.io

13.4 Class Object Member


Classes are user defied data types UDT we can use them to
define members of other classes, for example we can define line
class that have starting and ending points, by using point class as its
data member see the following program

Program 13.4
1 // class object member to object
2 #include<iostream>
3 using namespace std;
4
5 class point {
6 private:
7 int x, y;
8
9 public:
10 point(int x, int y){
11 this->x = x;
12 this->y = y; }
13 };
14
15 class line {
16 private:
17 point start, end;
18 public:
19 line(int x1, int y1, int x2, int y2):
20 start(x1, y1), end(x2, y2){
21 }
22 };
23
24 int main () {
25 line *myline;
26 myline = new line(5,4,8,9);
27
28 delete myline;
29
30 return 0;
31 }
32
33

©Saif Bashar 2019


CHAPTER 13 Saif.io

Exercises 13

Q1: Write an object-oriented program in C++ that represent the


rectangle class, define two data members, with constructor
overloading, add a member function outside the class for printing,
then define four rectangle objects, use friend function to find the
biggest rectangle area.
Video lecture: Solution for Q1 - Exercises 13
https://youtu.be/RCF1m62FfrE

Q2: Write an object-oriented program in C++ to represent 20


students, the class constructor will set the values to all data members
for each student, then calculate the average for each student using
friend function.
Video lecture: Solution for Q2 - Exercises 13
https://youtu.be/29NeWoONJIc

©Saif Bashar 2019


Chapter 14
Operators Overloading
14.1 Introduction
14.2 Overloading Unary Operators
14.3 Overloading Binary Operators
Exercises 14

s a i f . i o
CHAPTER 14 Saif.io

14.1 Introduction
We came across the term overloading when we discussed
function overloading in Chapter 5 and constructor overloading in
Chapter 11, the word overloading means giving more than one job
to something.

Function overloading is when we have the same function perform


different tasks the intended function is called depending on its
argument list. The same definition applied to constructor
overloading.

This chapter present a new OOP feature that apply overloading to


the C++ language operators, to make the operator perform
additional tasks beside the built-in task it assigned to. Before we
discuss operators overloading, we have seen and worked in the
previous chapters of this book with various types of operators like
arithmetic, comparison, logical, bitwise, addressing and other
operators, now let us organize these operators depending on their
operands.

Operators

Unary Binary Ternary

If the operator takes only one operand it is called unary operator, if


the operator takes two operands it is called binary operator, and if it
takes three operands it is called ternary operator.

©Saif Bashar 2019


CHAPTER 14 Saif.io

For example:

++A the increment operator ++ is considered unary operator


because it takes only one operand A.

A + B the addition operator + is considered a binary operator


because it takes two operands A and B.

A > B ? true : false; the conditional operator ?: is considered


a ternary operator because it takes three operands: A>B, true and
false.

Note that some operators can beave as unary and binary in


defferent functionality, for example the minus sign – is considered
unary operator while the subtraction sign – is binary operator.

-A; // minus sign unary operator


A-B; // subtraction sign unary operator

The most common operators are:

Operators

Unary Binary Ternary


- + += ?:
* - -=
& * *=
++ / /=
-- % %=
sizeof
^ & |
!
~ . ->
|| &&
>> <<
> < >=
<=
::

©Saif Bashar 2019


CHAPTER 14 Saif.io

Warning

All the operators mentioned above can be overloaded


except:

:: the scope resolution operator


?: the conditional operator
. the member access operator
sizeof size of operator

The idea behind operators overloading is to make the operators that


works on simple data types also can work on objects, for example
the increment operator ++ is defined in the language to work on
numbers, we can overload this operator by adding additional
functionality to it to make it work on objects also as we will see in the
upcoming section.

14.2 Overloading Unary Operators


As we stated above unary operators take only one operand, in order
to overload an operator to make it operate one objects we need to
include a special member function named with the operator symbol
preceded with the keyword operator.

For example, if we have the following student class, and we wanted


to increment the student age by one, we need to implement a
member function to do that. See Program 14.1

The member function simply increments the age data member by


one when called in the main function Line 36.

We can overload the increment operator and make it work with


objects so we can do this:
++s;

Instead of this:
s.incAge();

©Saif Bashar 2019


CHAPTER 14 Saif.io

Program 14.1
1 // Student Class
2 #include<iostream>
3 using namespace std;
4 class student {
5 private:
6 string Name;
7 int ID, Age, Deg1, Deg2, Deg3;
8 public:
9 student(){
10 cout<<"Enter student ID: "; cin>>ID;
11 cout<<"Enter student Name: "; cin>>Name;
12 cout<<"Enter student Age: "; cin>>Age;
13 cout<<"Enter student Deg1: "; cin>>Deg1;
14 cout<<"Enter student Deg2: "; cin>>Deg2;
15 cout<<"Enter student Deg3: "; cin>>Deg3;
16 }
17
18 void incAge(){
19 Age++;
20 }
21
22 void print(){
23 cout<<"Student Name "<<Name<<endl;
24 cout<<"Student ID: "<<ID<<endl;
25 cout<<"Student Age: "<<Age<<endl;
26 cout<<"Student Deg1: "<<Deg1<<endl;
27 cout<<"Student Deg2: "<<Deg2<<endl;
28 cout<<"Student Deg3: "<<Deg3<<endl;
29 }
30 };
31
32 int main(){
33 student s;
34
35 s.incAge();
36 s.print();
37
38 return 0;
39 }
40

©Saif Bashar 2019


CHAPTER 14 Saif.io

Now to make the following statement work:

++s;

We need to add a special function inside the call we will name the
function ++ preceded with the keyword operator, this function will be
added:

void operator ++(){

++Age;

We can rewrite Program 14.1 adding the unary ++ overloaded


operator, see Program 14.2, note the operator overloading function
does not return a value to the calling line so we need to give it void
as a return type.

Also note that if we write in postfix notation:

s++;

We need to implement another function to overload the postfix


increment operator

void operator ++(int){

Age++;

Note that the int added to the argument for the compiler to not
confuse it with the prefix increment operator, the argument list must
be unique for each function with the same name, remember this
was a condition for function overloading, so here we have
overloaded function for operator overloading, see the Program 14.3
both functions are added.

Video lecture: Operators Overloading (Unary Operators)


https://youtu.be/07x82MzCHDo

©Saif Bashar 2019


CHAPTER 14 Saif.io

Program 14.2
1 // Unary Overloading
2 #include<iostream>
3 using namespace std;
4 class student {
5 private:
6 string Name;
7 int ID, Age, Deg1, Deg2, Deg3;
8 public:
9 student(){
10 cout<<"Enter student ID: "; cin>>ID;
11 cout<<"Enter student Name: "; cin>>Name;
12 cout<<"Enter student Age: "; cin>>Age;
13 cout<<"Enter student Deg1: "; cin>>Deg1;
14 cout<<"Enter student Deg2: "; cin>>Deg2;
15 cout<<"Enter student Deg3: "; cin>>Deg3;
16 }
17
18 void print(){
19 cout<<"Student Name "<<Name<<endl;
20 cout<<"Student ID: "<<ID<<endl;
21 cout<<"Student Age: "<<Age<<endl;
22 cout<<"Student Deg1: "<<Deg1<<endl;
23 cout<<"Student Deg2: "<<Deg2<<endl;
24 cout<<"Student Deg3: "<<Deg3<<endl; }
25
26 void operator ++(){
27 ++Age; }
28 };
29
30 int main(){
31 student s;
32 ++s;
33 s.print();
34
35 return 0;
36 }
37
38
39
40
41

©Saif Bashar 2019


CHAPTER 14 Saif.io

Program 14.3
1 // Unary Overloading
2 #include<iostream>
3 using namespace std;
4 class student {
5 private:
6 string Name;
7 int ID, Age, Deg1, Deg2, Deg3;
8 public:
9 student(){
10 cout<<"Enter student ID: "; cin>>ID;
11 cout<<"Enter student Name: "; cin>>Name;
12 cout<<"Enter student Age: "; cin>>Age;
13 cout<<"Enter student Deg1: "; cin>>Deg1;
14 cout<<"Enter student Deg2: "; cin>>Deg2;
15 cout<<"Enter student Deg3: "; cin>>Deg3;
16 }
17
18 void print(){
19 cout<<"Student Name "<<Name<<endl;
20 cout<<"Student ID: "<<ID<<endl;
21 cout<<"Student Age: "<<Age<<endl;
22 cout<<"Student Deg1: "<<Deg1<<endl;
23 cout<<"Student Deg2: "<<Deg2<<endl;
24 cout<<"Student Deg3: "<<Deg3<<endl; }
25
26 void operator ++(){
27 ++Age; }
28
29 void operator ++(int){
30 Age++; }
31
32 };
33
34 int main(){
35 student s;
36 ++s; // s++ also do the same thing
37 s.print();
38
39 return 0;
40 }
41

©Saif Bashar 2019


CHAPTER 14 Saif.io

We can apply the same steps above to overload the decrement


operator in both notations the prefix and the postfix.

14.3 Overloading Binary Operators


The largest group of operators are binary operator, we can overload
binary operators like we did with unary operators with some
differences. We know that binary operators take two operands and
should return a value. Since we are working with objects, overloaded
binary operators work on objects and return a new object as a result
to the intended operation.

Let’s take an example on adding two vectors, for simplicity let’s


suppose a vector has only a starting point with two coordinates so in
order to add two vectors we intend to add the corresponding
coordinates to produce a new vector that represent the summation
of two vectors, so we will overload the + operator.

©Saif Bashar 2019


CHAPTER 14 Saif.io

Program 14.4
1 // Binary Overloading
2 #include<iostream>
3 using namespace std;
4 class vector {
5 private:
6 int x, y;
7 public:
8 vector(int a, int b){
9 x=a;
10 y=b;
11 }
12
13 void print(){
14 cout<<"X = "<<x<<" Y = "<<y<<endl;
15 }
16
17 vector operator +(vector v2){
18 vector v3(x + v2.x, y + v2.y);
19 return v3; }
20
21 };
22
23 int main(){
24 vector v1(1,2), v2(3,4);
25
26 v1.print();
27 v2.print();
28
29 vector v3 = v1 + v2;
30
31 v3.print();
32
33 return 0;
34 }

Video lecture: Operators Overloading (Binary Operators)


https://youtu.be/vVfDnyQsQt0

©Saif Bashar 2019


CHAPTER 14 Saif.io

Exercises 14

Q1: Write an object-oriented program in C++ that overload the +


operator to concatenate two strings.
Video lecture: Solution for Q1 - Exercises 14
https://youtu.be/CE9s0MVMR2w

Q2: Write an object-oriented program in C++ that overload the


subscript [ ] operator.
Video lecture: Solution for Q2 - Exercises 14
https://youtu.be/AMMahVZEpZU

©Saif Bashar 2019


Chapter 15
Inheritance
15.1 Introduction
15.2 Single Inheritance
15.3 Multiple Inheritance
15.4 Hierarchical Inheritance
15.5 Multilevel Inheritance
15.6 Private, Public and Protected Inheritance
15.7 Overriding Methods
15.8 Virtual Functions
Exercises 15

s a i f . i o
CHAPTER 15 Saif.io

15.1 Introduction
Another fundamental concept in object-oriented programming
is the concept of inheritance, it is considered the third pillar of OOP in
addition to encapsulation and polymorphism.

Inheritance also called code reuse, code reuse means that when we
build a class for a particular concept, we can use this class and
inherit its functionality solving some problem, this mechanism will save
huge amount of time since we can reuse classes already had been
built without the need to rebuild them.

This chapter present a new OOP feature which is inheritance and


illustrate the basic types of inheritance and how to implement them
in C++ language, but before we start, we need to know some basic
definitions.

Base class: it is the class that we want to reuse its code (data
members, member functions), also called parent class or superclass
in java language.

Derived class: it is the class that is using the data and/or functionality
of the base class through inheritance, also called child class or sub
class in java language.

There are many types of inheritance depending on the connection


between the base class (classes) and the derived class (classes),
Figure 15.1 illustrate the basic types.

Inhritance

Sinlge Multiple Multilevel Heirachical Hybrid

Figure 15.1, Inheritance Types

©Saif Bashar 2019


CHAPTER 15 Saif.io

15.2 Single Inheritance


The simplest type it has a single base class and a single derived class,
the data members and member function are inherited by the
derived class directly.

As we have seen in the previous chapters, classes are meant to


represent the real world we can represent anything in the world in
classes, in inheritance the base class can be thought of the more
general class and the derived class is the more specific class, to
illustrate this idea lets take an example from the real world. If we
wanted to represent a person in class and a student in another class,
we can represent them in separate classes each of which have its
own data members and member functions, but there are many
data member that are common in both classes, every person has a
name, age, length, weight, etc. also every student has a name, age,
length, weight, etc. so instead of redundantly writing these data in
both classes we can write then once in the base class and reuse
them in the derived class.

Here we have the class person is the base class because it is the
more general concept, and the student class is considered the
derived class because it is the more specific concept. We can say
every student is a person but not every person is a student.

Program 15.1 implement both classes, not the base class person is
written first then the derived class student came second.

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.1
1 #include<iostream>
2 using namespace std;
3 class person {
4 private:
5 string name;
6 int age, length, weight;
7 public:
8 person(){
9 cout<<"Enter Name: "; cin>>name;
10 cout<<"Enter Age: "; cin>>age;
11 cout<<"Enter Length: "; cin>>length;
12 cout<<"Enter Weight: "; cin>>weight; }
13
14 void print(){
15 cout<<"Name: "<<name<<endl;
16 cout<<"Age: "<<age<<endl;
17 cout<<"Length: "<<length<<endl;
18 cout<<"Weight: "<<weight<<endl; }
19 };
20
21 class student : public person {
22 private:
23 int level;
24 float avg;
25 public:
26 student(){
27 cout<<"Enter Average: "; cin>>avg;
28 cout<<"Enter Level: "; cin>>level; }
29
30 void print(){
31 person::print();
32 cout<<"Average: "<<avg<<endl;
33 cout<<"Level: "<<level<<endl; }
34 };
35
36 int main(){
37 student s;
38
39 s.print();
40
41 return 0; }

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.1 Line 21

class student : public person

This line mean connect the class student with the class person using
the colon operator ( : ) here the person class is the base class and
the student class is the derived class. The inheritance type is public
more on this later.

We can visualize the single inheritance with Figure 15.2

Person

Student
Figure 15.2, Single Inheritance

Note that creating an object from the derived class will


automatically trigger the base class constructor then the derived
class constructor.

If we want to send values in the derived class object’s definition take


a look at Program 15.2

Lines 26 and 27 the head of the student constructor will receive all
the data from the main function and pass the inherited data to the
parent constructor the person constructor, and take the values of
level and avg to the student’s data member

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.2
1 #include<iostream>
2 using namespace std;
3 class person {
4 private:
5 string name;
6 int age, length, weight;
7 public:
8 person(string n, int a, int len, int w){
9 name=n;
10 age=a;
11 length=len;
12 weight=w; }
13
14 void print(){
15 cout<<"Name: "<<name<<endl;
16 cout<<"Age: "<<age<<endl;
17 cout<<"Length: "<<length<<endl;
18 cout<<"Weight: "<<weight<<endl; }
19 };
20
21 class student : public person {
22 private:
23 int level;
24 float avg;
25 public:
26 student(string n, int a, int len, int w,
27 float v, int lev): person(n, a, len, w){
28 avg=v;
29 level=lev; }
30
31 void print(){
32 person::print();
33 cout<<"Average: "<<avg<<endl;
34 cout<<"Level: "<<level<<endl; }
35 };
36
37 int main(){
38 student s ("ali",20,170,75,95,2);
39 s.print();
40
41 return 0; }

©Saif Bashar 2019


CHAPTER 15 Saif.io

Important note: the inherited data from the base class cannot be
accessed directly in the derived class due to encapsulation, if we
want to access these data directly, we need to use the access
specifier protected in the base class, protected means the data will
be private in both the base and the derived classes.

Video lecture: Inheritance (Single Inheritance)


https://youtu.be/1nhIK34BEyY

Video lecture: Inheritance (Single Inheritance with constructors)


https://youtu.be/FOh-jjmVFt8

15.3 Multiple Inheritance


This type of inheritance when we have more than one base class to
a derived class as illustrated in the Figure 15.3

Figure 15.3, Multiple Inheritance

The derived class will inherit the data members and member
functions of both base classes, let carry on the same previous
example by adding another class gradStudent that represent a
graduate student, that will inherit from the person and the student
classes, see Program 15.3

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.3
1 #include<iostream>
2 using namespace std;
3 class person {
4 private:
5 string name;
6 int age;
7 public:
8 person(string n, int a){
9 name=n;
10 age=a; }
11
12 void print(){
13 cout<<"Name: "<<name<<endl;
14 cout<<"Age: "<<age<<endl;}
15 };
16
17 class student {
18 private:
19 int level;
20 float avg;
21 public:
22 student(float v, int lev){
23 avg=v;
24 level=lev; }
25
26 void print(){
27 cout<<"Average: "<<avg<<endl;
28 cout<<"Level: "<<level<<endl; }
29 };
30
31 class gradStudent: public person, public
32 student {
33 private:
34 string research;
35 public:
36 gradStudent(string n, int a, float v, int
37 lev, string r):person(n,a),student(v,lev)
38 {
39 research=r; }
40

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.3 (cont.)


41
42 void print(){
43 person::print();
44 student::print();
45 cout<<"Research: "<<research<<endl; }
46 };
47
48 int main(){
49 gradStudent s ("Sara",20,75,2,"AI");
50 s.print();
51
52 return 0; }

Lines 31 and 32 specify the multiple inheritance by specifying both


base classes person and student.

Lines 36 and 37 the derived class constructor invoke the parent


classes constructors and sending the appropriate data.

Video lecture: Multiple Inheritance


https://youtu.be/-CsX5AAU9U0

15.4 Hierarchical Inheritance


Hierarchical inheritance is the opposite of the multiple inheritance,
here we have one base class and multiple derived classes, as
illustrated in Figure 15.3

Base Class

Derived 1 Derived 3 Derived 3


Figure 15.3, Hierarchical Inheritance

©Saif Bashar 2019


CHAPTER 15 Saif.io

For example id we have an Employee class with the data members


(name, age, salary) and we derive a class of Manager that will
inherit all the data from the employee class and has the data
member (title as string), another derived class Scientist also will inherit
from the employee class with a data member of its own (publication
as string), the third class is Worker will inherit from the employee class
with no data of its own, the three classes are illustrated in Figure 15.4

Employee

Manager Scientist Worker


Figure 15.4, Hierarchical Inheritance

Program 15.4 implement the four classes with the appropriate


inheritance connections, and constructors’ callings.

Line 19 connects the Manager class with the Emp class

Line 32 connects the Scientist class with the Emp class

Line 47 connects the Worker class with the Emp class

The appropriate data are assigned to the classes data members and
the base class data are sent to the base class constructor from the
derived classes constructors.

Video lecture: Hierarchical Inheritance


https://youtu.be/UYvHqAug-rE

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.4
1 #include<iostream>
2 using namespace std;
3 class Emp {
4 private:
5 string name;
6 int age, salary;
7 public:
8 Emp(string n, int a, int s){
9 name=n;
10 age=a;
11 salary=s; }
12
13 void print(){
14 cout<<"Name: "<<name<<endl;
15 cout<<"Age: "<<age<<endl;
16 cout<<"Salary: "<<salary<<endl;}
17 };
18
19 class Manager : public Emp{
20 private:
21 string title;
22 public:
23 Manager(string n, int a, int s, string t):
24 Emp(n, a, s){
25 title=t; }
26
27 void print(){
28 Emp::print();
29 cout<<"Title: "<<title<<endl; }
30 };
31
32 class Scientist: public Emp {
33 private:
34 string publication;
35 public:
36 Scientist(string n, int a, int s, string p):
37 Emp(n,a,s){
38 publication=p; }
39
40

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.4 (cont.)


41
42 void print(){
43 Emp::print();
44 cout<<"Publication: "<<publication<<endl; }
45 };
46
47 class Worker: public Emp {
48 public:
49 Worker(string n, int a, int s): Emp(n,a,s){ }
50
51 void print(){
52 Emp::print();}
53 };
54
55 int main(){
56
57 Manager *M;
58 M = new Manager ("Ali",54,7000,"HR Manager");
59 M->print();
60
61 Scientist *S;
62 S = new Scientist ("Ahmed",43,5000,"AI Tech.");
63 S->print();
64
65
66 Worker *W;
67 W = new Worker("Hasan",22,2000);
68 W->print();
69
70 delete M;
71 delete S;
72 delete W;
73
74 return 0;
75
76 }
77
78
79
80

©Saif Bashar 2019


CHAPTER 15 Saif.io

15.5 Multilevel Inheritance


Multilevel inheritance is when we have more than one level of
inheritance, it is the type when a derived class become a base class
to another class, as illustrated in Figure 15.5

Base Class

Derived 1

Derived 2
Figure 15.5, Multilevel Inheritance

The derived 1 class will be a derived class from the base class and a
base class for the derived 2 class. The most general concept is
considered a first level base class, the next specific class is
considered the base class for the more specific class and so on. This
process can be extended to any number of levels, to illustrate the
idea let’s take the following example:

Since every manager is an employee and every employee is a


person we can organize the three classes in the following multilevel
inheritance, as the following figure explain, and program 15.5 as the
implementation of these classes.

Person

Employee

Manager

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.5
1 #include<iostream>
2 using namespace std;
3 class Person {
4 private:
5 string name;
6 int age;
7 public:
8 Person(string n, int a){
9 name=n;
10 age=a; }
11
12 void print(){
13 cout<<"Name: "<<name<<endl;
14 cout<<"Age: "<<age<<endl; }
15 };
16
17 class Emp : public Person{
18 private:
19 int salary;
20 public:
21 Emp(string n, int a, int s):Person(n,a){
22 salary=s; }
23
24 void print(){
25 Person::print();
26 cout<<"Salary: "<<salary<<endl; }
27 };
28
29 class Manager : public Emp{
30 private:
31 string title;
32 public:
33 Manager(string n, int a, int s, string t):
34 Emp(n, a, s){
35 title=t; }
36
37 void print(){
38 Emp::print();
39 cout<<"Title: "<<title<<endl; }
40 };

class Scientist: public Emp {


private:
string publication;
©Saif Bashar 2019
public:
CHAPTER 15 Saif.io

Program 15.5 (cont.)


41
42 int main(){
43
44 Manager M ("Ali",54,7000,"HR Manager");
45 M.print();
46
47 Emp A("Ahmed",43,5000);
48 A.print();
49
50
51 Person S ("Saif",34);
52 S.print();
53
54 return 0; }

Video lecture: Multilevel Inheritance


https://youtu.be/YhiGXZdQul8

The Hybrid Inheritance is in fact the combination of two or more


types of inheritance with the same methodologies used in
connecting the classes and constructors. For example, combining
the multilevel inheritance with hierarchical inheritance we may have
the following figure

Base Class

Derived 1 Derived 2

Derived 3
Figure 15.6, Hybrid Inheritance

©Saif Bashar 2019


CHAPTER 15 Saif.io

15.6 Private, Public and Protected Inheritance


There are access specifiers for the inheritance they can be specified
by the following table:

Derived Class
Base Class Data Public Private Protected
Inheritance Inheritance Inheritance
• Private • No Access • No Access • No Access
• Protected • Protected • Private • Protected
• Public • Public • Private • Protected

For example, if the base class has public data and methods and the
inheritance specifier was private:

class baseClass : private derivedClass

this means that the inherited data and methods will be private in the
derivedClass.

Video lecture: Multilevel Inheritance


https://youtu.be/YhiGXZdQul8

15.7 Overriding Methods


The concept of Methods overriding simply means that if you have a
method in the derived class and an inherited method with the same
name in the base class and you created an object from the derived
class and called this method. Which one will be executed? The
method in the derived class or the inherited method?

The answer is the method in the derived class will be executed, we


say the method in the derived class will override the inherited
method that has the same name. for example, see Program 15.6

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.6
1 #include<iostream>
2 using namespace std;
3 class A {
4 public:
5 void test(){
6 cout<<"this is a test from A class"<<endl;
7 }
8 };
9
10 class B : public A{
11 public:
12 void test(){
13 cout<<"this is a test from B class"<<endl;
14 }
15 };
16
17
18 int main(){
19
20 A Obj1;
21 Obj1.test();
22
23 B Obj2;
24 Obj2.test();
25
26 Obj2.A::test();
27
28 return 0;
29 }

The output will be:

this is a test from A class


this is a test from B class
this is a test from A class

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.6 Line 20, declare an object from the base class. Line 21
call the member function of the base class (no inheritance here).

Line 23, declare an object from the derived class (which now has
two test methods). Line 24 call the test method of the derived class,
the test method of the derived class will override the test method in
the base class.

Line 25, call the test method of the base class canceling the
overriding feature.

The benefit of the override feature is that we can customize the


methods in the base class without changing their code.

Video lecture: Methods Overriding


https://youtu.be/SLkCGDIIhuA

15.8 Virtual Functions


There is a problem in inheritance that will appear if we have the
following:
• Inheritance of any type
• Overridable method (method with the same name in base and
derived classes)
• Pointer to object in the main function

For example, if we have the following classes all of them have the
area () method: (Program 15.7)

Shape

Square Cirlce

©Saif Bashar 2019


CHAPTER 15 Saif.io

Program 15.7
1 #include<iostream>
2 using namespace std;
3 class Shape {
4 public:
5 void area(){
6 cout<<"this is a shape area"<<endl;
7 }
8 };
9
10 class Square : public Shape{
11 public:
12 void area(){
13 cout<<"this is a square area"<<endl;
14 }
15 };
16
17 class Circle : public Shape{
18 public:
19 void area(){
20 cout<<"this is a circle area"<<endl;
21 }
22 };
23
24 int main(){
25
26 Square S;
27 Circle C;
28
29 Shape *Sh1 = &S;
30 Sh1->area();
31
32 Shape *Sh2 = &C;
33 Sh2->area();
34
35 return 0;
36 }
37
38
39
40

©Saif Bashar 2019


CHAPTER 15 Saif.io

Lines 26, define an object from the derived square class, Line 27
define an object from the derived class circle.

Line 29, define a pointer to object of the base class that points to the
square object defined earlier, Line 30 calling the area method for this
pointer to object will invoke the area of the base class, the override
feature now is broken.

Line 32, define a pointer to object of the base class that points to the
circle object defined earlier, Line 33 calling the area method for this
pointer to object will invoke the area of the base class, the override
feature now is broken.

We use the virtual function in this situation to restore the override


feature, so the area method of the base class should be like this:

virtual void area(){


cout<<"this is a shape area"<<endl;
}

By adding the keyword virtual the appropriate method will be


called at runtime this is called dynamic dispatching or (late binding)
and it is a type of polymorphism.

Virtual function: is an inheritable and overridable function or method for which


dynamic dispatch is facilitated. This concept is an important part of the (runtime)
polymorphism a virtual function defines a target function to be executed, but the
target might not be known at compile time.

Note that the virtual function if it was empty it is called pure virtual
function written like this

virtual void area()=0;

Video lecture: Virtual Functions


https://youtu.be/ZMYkxtVXcq8

©Saif Bashar 2019


Chapter 16
Templates
16.1 Introduction
16.2 Single Inheritance
16.3 Multiple Inheritance
16.4 Hierarchical Inheritance
Exercises 16

s a i f . i o
CHAPTER 16 Saif.io

16.1 Introduction
Templates are considered a useful technique in programming
with C++, it allows us to build programs that will work on multiple
data types.

For example, if we have a program for the stack data structure (or
any data structure) we know that it has an array that will hold the
items that we want to push inside this stack, we have to define this
array and specify a data type to this array.

By specifying a fixed data type for this array, we can work only with a
stack that holds integers, if we wanted to work with a stack that
holds characters, we need to build another stack program for that.

Fortunately, there is another way that enable us to work with the


stack with any data type that we want by implementing only one
program by using a technique called templates.

16.2 Function Templates


We can write templates for functions and classes, let’s talk first about
function templates.

Suppose you want to build a function that return the max number
from two numbers, you may code it like the following simple program
16.1:

©Saif Bashar 2019


CHAPTER 16 Saif.io

Program 16.1
1 #include<iostream>
2 using namespace std;
3
4 int maximum(int n1, int n2) {
5 if(n1 > n2)
6 return n1;
7 else
8 return n2;
9 }
10
11 int main(){
12
13 int number1, number2;
14 cout<<"Enter Two Numbers: ";
15 cin>>number1>>number2;
16
17 cout<<maximum(number1, number2) <<endl;
18
19 return 0;
20 }

Now what if you want to test two float numbers, or two doubles or
even two characters, you have to build a function for every data
type.

There is a way by building only one function and it will work for any
data type that we give it using the template technique, see the
following program 16.2

©Saif Bashar 2019


CHAPTER 16 Saif.io

Program 16.2, Finding the maximum using template function

1 #include<iostream>
2 using namespace std;
3
4 template <class T>
5
6 T maximum(T n1, T n2) {
7 if(n1 > n2)
8 return n1;
9 else
10 return n2;
11 }
12
13 int main(){
14
15 int number1, number2;
16 cout<<"Enter Two Numbers: ";
17 cin>>number1>>number2;
18
19 cout<< maximum(number1, number2)<<endl;
20
21 char char1, char2;
22 cout<<"Enter Two Characters: ";
23 cin>> char1>> char2;
24
25 cout<< maximum(char1, char2)<<endl;
26
27 float f1, f2;
28 cout<<"Enter Two Floats: ";
29 cin>> f1>> f2;
30
31 cout<< maximum(f1, f2)<<endl;
32
33 return 0;
34 }
35
36
37
38
39
40

©Saif Bashar 2019


CHAPTER 16 Saif.io

Note that in program 16.2 we built one function that can handle
three different data types, in Line 19 we sent two integers, in Line 25
we sent two characters, in Line 31 we sent two floats.

The template statement in Line 4 declares T as a class template also


called template argument, that will take any data type we specify,
simply T will be replaced by the type of the passed parameters at
runtime.

We say that the function maximum is a template function that works


on any data type the we pass to it. The compiler will generate the
function code for the passed argument when the function is called.

Let’s take another example, for finding an element and return its
index see program 16.3

Program 16.3 illustrate the idea of function template by using a single


function to search arrays of different types.

Line 17 we passed an array of integers and an integer value to find


its location in the array

Line 20 we passed an array of characters and a character to find its


location in the array

Line 23 we passed an array of floats and a float number to find its


location in the array

©Saif Bashar 2019


CHAPTER 16 Saif.io

Program 16.3, Finding the location of an element using


template function

1 #include<iostream>
2 using namespace std;
3
4 const int size = 5;
5 template <class S>
6
7 int find(S array[size], S element) {
8
9 for(int i=0; i<size; i++)
10 if(array[i]== element)
11 return i;
12 }
13
14 int main(){
15
16 int a[size] = {1, 2, 3, 4, 5};
17 cout<< find(a, 4)<<endl;
18
19 char c[size] = {'a', 'b', 'c', 'd', 'e'};
20 cout<< find(c, 'e')<<endl;
21
22 float f[size] = {1.3, 3.4, 6.5, 7.9, 8.5};
23 cout<< find(f, 1.3)<<endl;
24
25 return 0;
26 }

©Saif Bashar 2019


CHAPTER 16 Saif.io

16.3 Class Templates


The idea of template is the same in classes we can build classes that
deal with different data types using a single class, rather than
building a class for each data type.

For example, the stack class, program 16.4

Program 16.4, implementing a stack class template


1 #include<iostream>
2 using namespace std;
3 template <class S>
4 class stack
5 {
6 S item[100];
7 int top;
8
9 public:
10 stack(){
11 top=-1; }
12
13 void push(S value){
14 item[++top]=value; }
15
16 S pop(){
17 return(item[top--]); }
18 };
19
20 int main() {
21 stack<int> s1;
22
23 s1.push(10);
24 cout<<s1.pop()<<endl;
25
26 stack<char> s2;
27 s2.push('A');
28 cout<<s2.pop()<<endl;
29
30 stack<string> s3;
31 s3.push("Saif");
32 cout<<s3.pop()<<endl;
33 }

©Saif Bashar 2019


CHAPTER 16 Saif.io

Note that we specified the type of the items array as a template


variable also the value in the push method’s argument and the
return type of the pop method.

We do not need to make the top variable as a template variable


because the top is always integer pointing at the top of the stack.

Lines 21 we specified the stack will work on integer values.

Lines 26 we specified the stack will work on characters values.

Lines 30 we specified the stack will work on string values.

And so on…

Video lecture: Templates


https://youtu.be/tXBEQl8U3sY

©Saif Bashar 2019


Abbreviations
ANSI American National Standards Institute
ASCII American Standard Code for Information Exchange
CPU Central Processing Unit
EDT Enumerated Data Type
GCC GNU Compiler Collection
GCD Greatest Common Divisor
IDE Integrated Development Environment
ISO International Standards Organization
OOP Object Oriented Programming
OS Operating System
php Hypertext Preprocessor
RAM Random Access Memory
UDT User Defined Type

You might also like