CPP PDF
CPP PDF
Programming
with
C++
PROCEDURAL PROGRAMMING &
OBJECT ORIENTED PROGRAMMING
SAIF BASHAR
Part 1
s a i f . i o
CHAPTER 00 Saif.io
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.
You can find other versions for other platforms at their official website at:
http://www.codeblocks.org
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:
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:
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.
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.
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
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
s a i f . i o
CHAPTER 01 Saif.io
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,
C++ also had gone through several updates and releases; every
release contains several upgrades adding new features removing
some and so on.
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.
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.
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.
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.
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++:
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.
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.
Editor
Prepocessor
Compiler
Linker
Loader
Execution
Exercises 1
Q1: Why it’s called C language?
s a i f . i o
CHAPTER 02 Saif.io
Value
Name Type
Identifiers Examples
Allowed:
my_number, x1, myNumber, pi, counter, INT, fi
Not Allowed:
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.
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.
Also note that the cin function use its own operator >> the extraction
operator for each variable you want to read.
2- float: used for decimal numbers positive and negative with less
precision.
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 }
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.
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:
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.
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);
int 4
float 4
double 8
char 1
long double 12
bool 1
long long 8
short 2
Now, if we know the data type size we can calculate its range, lets
calculate the range of the int data type:
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.
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.
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
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.
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);
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 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.
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
3.14
S
1
Video lecture: Basic Data Types Video lecture: Notes on Data Types
https://youtu.be/JRq6Ga1n_gU https://youtu.be/p9hcOeW9Y3Y
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.
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;
Also note that the remainder operator only works with integers it
doesn’t work with float or double operands.
Make Examples
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.
int a=50, b;
b = ++a;
cout<<b<<" "<<a;
int a=50, b;
b = a++;
cout<<b<<" "<<a;
int a=50;
++a;
cout<<a;
it means add 10 to the old value of a and store the new value in a,
the same goes for -=, *=, /= and %=
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.
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.
Operator Operation
() Parenthesis
- Negative Sign
*, /, % Multiplication, Division and Remainder
+, - Addition and Subtraction
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.
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.
The following code will produce 9, 6, 4 can you figure out why?
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.
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
Math Functions
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.
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 we take a simple quadratic equation where a=1, b=6, c=8 like this
one:
x2 +6x+8=0
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.
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.
Exercises 2
Q1: Find the value if A where A = (5+2*3+((3-2) *7) + -9) / 2
Q2: Write C++ program to read x and compute sin(x), cos(x) and
tan(x)
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
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.
if (expression)
statement1;
else
statement2;
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.
if Statement Syntax
if (expression)
statement1;
if (expression)
{statement1;
statement2;}
else
{statement3;
statement4;
statement5;}
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)
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 }
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.
Logical Operators
Operator Operation Example
! NOT if (!a)
&& AND if (a>=b && b!=5)
|| OR if (a<=b || b==9)
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.
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.
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 }
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 }
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
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.
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.
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 }
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.
A B A XOR B
false false False
false true True
true false True
true true false
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.
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
We can use the shortcuts like we did with the arithmetic operators
like the following table:
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
This video explains the bitwise operators, and how to convert from
decimal to binary system.
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.
Mixed Operators
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.
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
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
𝑥 2 + 5𝑥 − 20
𝑖𝑓 𝑥 > 0
𝑦= √2𝑥
0 𝑖𝑓 𝑥 = 0
2
{ 𝑥 + 10𝑥 − 10 𝑖𝑓 𝑥 < 0
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
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
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
Q14: Solve the following Expressions (find the value of m with steps):
x = 11
m = (6>1) | (6^16) & x++
-------------------------------------------------------
x = 10
m = (6<1) | (20^16) & x++ + 1
Q15: Find the value of B for the following expression (with steps):
i=5
j=9
B = !((i>0) && (i>=j))
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)
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.
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.
Printing numbers from 1 to 100, the code will be something like this:
for (int i=1; i<=100; i++){
cout<<"Loop: "<<i<<endl; }
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.
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++;
}
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.
initialization;
while (stopCondition){
statement1;
statement2;
statement3;
step; } //end of while block
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.
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?
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; }
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 }
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 }
*****
*****
*****
*****
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 }
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.
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.
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 }
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:
Exercises 4
Q1: Write a program that displays the first 100 odd number using
while loop
𝑦 = 1 − 𝑥2 + 𝑥3 + 𝑥4 … … 𝑥𝑛
Video lecture: Solution for Q7 - Exercises 4
https://youtu.be/jH-XVRTOfSQ
𝑥 𝑥2 𝑥3 𝑥𝑛
𝑒 =1+ + + ……
1! 2! 3! 𝑛!
Video lecture: Solution for Q9 - Exercises 4
https://youtu.be/_vTWN2iXUxY
𝑠𝑢𝑚1 = 1 + 22 + 42 … … 𝑛2
𝑠𝑢𝑚2 = 1 − 3𝑥 + 5𝑥 − … … 𝑛𝑥
1 2 3 𝑛
𝑠𝑢𝑚3 = 1 + + + ……
1! 2! 3! 𝑛!
while (i>0);
while (count<=10);
if(x % 3 == 0)
break;
cout<<"bottom of loop"<<endl;
}
switch (count%10){
cout<<endl<<"goodbye";
{ 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…";
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
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:
1
21
321
4321
54321
++++++++++
+++++++++
++++++++
+++++++
++++++
++++
+++
++
+
1
333
55555
7777777
999999999
7777777
55555
333
1
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.
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.
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
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.
returnType functionName(arguments){
statement1;
statement2;
statement3;
return value;
} //end of function block
Function Calling
int main(){
Note that we can call a function from the main function or from any other
user defined function.
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.
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;
}
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
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.
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.
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);
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
Functions
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; }
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.
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.
int main(){
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.
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
names it won’t affect the program, the following implementation will work
too:
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.
int main(){
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.
Try to test the reference operator to see that it gives you the variable’s
address in hexa-decimal value:
Here a, b and c are pointers that points to the original values of the
variables in the main function.
return (a+b+c)/3.0;
int main(){
cout<<v;
return 0;
Passing Parameters
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; }
Note that the original values did not swap because we were swapping the
copies not the original values.
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; }
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; }
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.
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.
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 }
cout<<msg;
}
print();
The default argument will give the value to the msg variable.
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
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.
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 }
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; }
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.
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.
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 like loops they need a stop condition called a base
case that stops the function from calling itself.
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 }
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
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.
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; }
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
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
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
Q8: Write a program using function to find the nth Fibonacci number
Video lecture: Solution for Q8- Exercises 5
https://youtu.be/pqBiu4CSClQ
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
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
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?
Defining an Array
dataType arrayName[size];
Defining an array called a with five integer elements, the code will
be like this:
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.
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;
10
20
30
40
50
int a[5]={10,20,30};
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};
Note that the loop’s counter started with zero, and ended with 4 as it
is the index of the last element.
cin>>a[0];
cin>>a[1];
cin>>a[2];
cin>>a[3];
cin>>a[4];
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 }
or use the preprocessor directive under the #include you can write:
#define size 5
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 }
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
Or like this:
int a[2][2]={10,20,30,40};
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
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 }
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.
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
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
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
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
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
1 2 3 6
𝑎=4 5 6 𝑏 = 15
7 8 9 24
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
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.
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.
char name[5]={’s’,’a’,’i’,’f’,’\0’};
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.
char name[5]="saif";
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;
#include <string.h>
strcpy(name1, name2);
Note that the old value of the first argument will be lost and replaced
by the value of the second argument.
strcat(name1, name2);
The old value of the first argument Ali will be concatenated with the
value of the second argument Ahmed to produce the string
AliAhmed.
cout<<strcmp(name1, name2)<<endl;
cout<<strcmp(name3, name4)<<endl;
cout<<strcmp(name2, name5)<<endl;
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 third output will be zero since both strings are equal.
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:
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;
string name;
getline(cin, name);
cout<<name;
firstName = "Salman";
lastName = "Khan";
fullName = firstName + lastName;
cout<<fullName; //SalmanKhan
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
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?
struct structName {
dataType member1;
dataType member2;
dataType member3;
};
struct student{
int id;
string name;
int age;
string address;
float mark1;
float mark2;
float mark3;
};
struct structName {
dataType member1;
dataType member2;
dataType member3;
}instance1, instance2, instance3;
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;
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 }
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;
};
sara.birthdate.day = 18;
sara.birthdate.month = 1;
sara.birthdate.year = 1999;
student students[100];
students[0].id = 10;
students[0].name = "Mohammed";
Exercises 8
Q1: Write a program that declare a structure for employees that
have the following members: (Name, Age, Address, Phone number
and Country)
o Info
▪ ID
▪ Name
▪ Age
o Home
▪ Street
▪ City
▪ State
o Birthdate
▪ Day
▪ Month
▪ Year
o StartDate
▪ Day
▪ Month
▪ Year
Employee
Code (integer)
Name (string)
Gender (EDT)
Degree (EDT)
Video lecture: Solution for Q3 - Exercises 8
https://youtu.be/qfVb_YHo48Y
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++:
The side figure shows that ptr is a pointer that hold the
variable’s p address in memory.
int a[3]={10,20,30};
int *ptr;
ptr = a;
cout<<*ptr<<endl;
cout<<*(++ptr)<<endl;
cout<<*(++ptr)<<endl;
Since the array’s name represent the address of the first element
then we don’t need to use the reference operator with arrays.
struct student{
long id;
string name;
int age;
string address;
float mark1;
float mark2;
float mark3;
};
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.
Exercises 9
Q1: Write a program that apply mathematical pointer operations
Video lecture: Solution for Q1 - Exercises 9
https://youtu.be/L1huH24P-l0
x=&c;
p=x+2;
q=x-2;
a=p-q;
cout<<x;
cout<<p;
cout<<q;
cout<<a;
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.
The next paragraphs will discuss the built-in C/C++ functions that
perform the above operations on files.
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.
So, for opening a file for writing named 1.txt inside our project
directory the code will be:
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);
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; }
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.
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);
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 }
#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.
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 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.
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.
After running this program, you can check the file out.txt in your
program folder to see its content.
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:
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
Part 2
s a i f . i o
CHAPTER 11 Saif.io
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++.
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.
I’m sorry that Ronaldo moved to Juventus and ruined this example for me.
But you get the idea.
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.
- Data abstraction
- Encapsulation (data hiding)
- Inheritance (reusability)
- Operator overloading
- Polymorphism
- Exception handling
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.
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.
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;
};
class rectangle {
private:
int width, length;
public:
int area(){
return width * length;
}
int circumference(){
return (width + length)*2;
} };
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.
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;
}
};
This will make all our rectangle objects have the same dimensions which is
clearly wrong.
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.
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 }
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:
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.
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 }
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; }
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.
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.
- Remove the object and free up the memory that was reserved for it.
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:
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 }
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; }
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
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 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.
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
return month;
Objects that are not constant can call constant member functions and
non-constant member functions.
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
s a i f . i o
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 }
Friend functions are useful when we want them to process data for
many objects belong to the same class or different classes.
So, we will create the class with the data members above then
create a constructor, and define three objects in the main function.
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 }
The following example illustrate two bank classes the second class is
a friend to the first class.
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; }
Exercises 12
s a i f . i o
CHAPTER 13 Saif.io
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
student s[SIZE];
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),
};
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 }
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.
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 }
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.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 }
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
Exercises 13
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.
Operators
For example:
Operators
Warning
Instead of this:
s.incAge();
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
++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:
++Age;
s++;
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.
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
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
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 }
Exercises 14
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.
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.
Inhritance
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.
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; }
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.
Person
Student
Figure 15.2, Single Inheritance
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
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; }
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.
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
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
Base Class
Employee
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.
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
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:
Person
Employee
Manager
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 };
Base Class
Derived 1 Derived 2
Derived 3
Figure 15.6, Hybrid Inheritance
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:
this means that the inherited data and methods will be private in the
derivedClass.
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 }
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.
For example, if we have the following classes all of them have the
area () method: (Program 15.7)
Shape
Square Cirlce
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
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.
Note that the virtual function if it was empty it is called pure virtual
function written like this
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.
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:
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
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
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.
Let’s take another example, for finding an element and return its
index see program 16.3
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 }
And so on…