Sample Chapters 1-10
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
CHAPTER 1-
THE EVOLUTION OF COMPUTER PROGRAMMING AND LANGUAGES:
AN OVERVIEW OF C AND C++
It is important to familiarize yourself with the fundamentals of computer programming, computer languages, and their evolution.
It may not be apparent to you at this time how this knowledge is going to help you to program in C/C++. It should, however,
be noted that within the past fifty years, a multitude of programming concepts and methods has been introduced, and many different
languages have been designed. Yet, they all still depend on a foundation that has remained relatively the same.
In this chapter, you are going to encounter unfamiliar terminology. What I would like you to do is to skim through this chapter
and grasp as much as you can, without attempting to understand everything fully. By examining the history of computer programming,
it is hoped that you will be able to better understand the way programming and languages are shaped, and have an idea as to
what to expect for the future of computer programming and languages
In order to give you a picture of computer programming and its abilities, I will introduce you to a very important program
that is known as a search, written in both C and C++. You will then experience what I call the magic of programming, where
the knowledge of building one program will lead you to build other programs without much effort. For example, you will see
how a Telephone Operator Search Program can also act as a language translator, a dictionary, and can also easily become a
bank or supermarket retrieval system.
I will conclude the chapter by giving examples of pitfalls in C/C++ programming that may cause misconceptions and delay learning.
These pitfalls, which are the result of hidden notions and unknown rules, are contributing factors to what I call the mystery
of C/C++ programming. You should be aware that the problems these pitfalls cause have nothing to do with your intelligence,
and that you will learn to solve them.
By going through the foundations of programming and languages you will find it easier to build programs from scratch using
C/C++ in the chapters that follow. |
Please choose from the following
|
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
CHAPTER 2
INPUT, PROCESS, OUTPUT (IPO)
The computer is in a constant cycle of input, process, and output. The computer waits for you to enter the required information
(input). Based on the entered information, the computer takes the appropriate actions (process). Finally, the result is displayed
on the screen or printed out (output). An analogy for input, process and output would be a food processor where food, fruit
and other ingredients are put into the machine. Afterward, based on the selected setting, such as cutting, chopping, or mixing,
the food processor performs the appropriate task, and finally the desired mixture is ready to be used.
THE MAIN SKELETON OF THE C AND C++ PROGRAM
A C/C++ program has a main skeleton, regardless of how large or small it is. Every program starts with the word main, followed
by an open parenthesis and closed parenthesis. The beginning of the program is marked with an open brace, and the end of the
program is marked with a closed brace. Let me show you the simplest program one can create in both C and C++.
The fact remains that this program does not perform any task, and its sole purpose is to illustrate the main skeleton of every
program. The word main in the program signifies that this is the main program (main function) where the main activities occur.
There are sub-programs (functions) that originate (called) from the main program. After the word main, you observed an open
parenthesis immediately followed by a closed parenthesis and nothing in between. The opening and closing braces indicates
a block where the program statements will be written in between.
|
Please choose from the following
|
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 3-LOOP: DOING IT OVER AND OVER LOOP AS A
LABOR FORCE One of the strengths of the computer is its ability to
repeat a process over and over without getting tired or threatening to
strike. The program that you have written to perform a single task can
now be repeated to perform the same task as many times as you wish.
This process of going over and over is known as repetition and is
called a loop. Can you think of a loop? Of course! Our everyday
activities, including getting up, eating, working, studying, and
sleeping are examples of a loop. Can you identify other loops? With a
little thought, I know you can. COMPUTERS IN THE LOOP Did you know that
your computer is in a constant cycle of input, process, and output?
This constant cycle of input, processing, and output means that your
computer is in a loop. It waits for you to enter data, takes your
input, analyzes it, performs the required task, and finally displays
the result. We can generalize and say that every automated system, from
the bank ATM machine, supermarket pricing, through the search engine of
the Internet all use the loop. WHAT DO YOU NEED TO MAKE A LOOP? It is
very simple to create a loop. Just follow these three steps: 1) Use a
reserved word (construct) from the C/C++ language to tell the program
to loop. 2) Set a condition as to whether to continue or to terminate
the loop. 3) Set aside the body of a loop to determine what you want to
loop. C/C++ LOOP CONSTRUCTS There are various ways to loop in a
program, and for each way there is a construct (reserve word) from
C/C++ that instructs the program to loop. These loop constructs are: 1)
while 2) for 3) do while 4) goto label Each of the above four loop
constructs can do the same job. However, some are better suited in some
situations and there are others that are rarely used, such as the goto.
For simplicity we will concentrate on the while command, and later the
others will be introduced. |
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 4-
Decision Making: making programs intelligent
Have you heard of computers that beat chess champions or mimic experts? The decision making statement responsible for making
a program an intelligent entity is known as the "if" statement. However, not using the proper decision-making can cause a
program to fail or possibly become dumb. This is known as a computer error. An example of a program error is to print or
display a paycheck for an employee who worked regular hours with a negative amount of money.
MAKING THE DECISION
If given an employee's salary, how would you determine the tax rate? If given the number of hours an employee worked, how
would you determine the overtime hours? If you were asked whether you want to continue, or stop what you are doing, what would
you answer? If you were asked to enter your password and you typed either the right or the wrong password, what would you
expect to happen? If given a menu with a list of items, how would you make a selection? These are a few examples of decision-making.
They are used in a similar fashion in programming.
HOW DO YOU MAKE A DECISION IN C/C++?
In C/C++, decision making is done by using an if or a switch statement. The if statement uses the form shown in Figure 4.1.
if( expression ){
//Body of if ( Runs only when the if expression is true )
}//IF
else {
// Body of else ( Runs only when the if expression is false )
}//ELSE
Figure 4.1 – The if / else structure of C/C++.
The expression after the if must evaluate to either true or false. If the expression evaluates to true, the “body of
the if”, which is the statement next to parentheses, will be executed. If the expression evaluates to false, the “body
of the else” will be executed. If the body of if or the body of else contain more than one statement, then braces {
} should be used. It is good practice to always use braces.
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 5-
ARRAY: ARRANGEMENT OF DATA
You may have heard the following expressions: array of flowers, array of thoughts, or an array of soldiers standing by. What
do all these expressions have in common? Each of the above has several alike elements that are arranged in order (one next
to the other). In the world of programming, an array has similar properties that are arranged in the memory cells (locations).
One cell follows another with each holding information of the same kind..
DEFINITION OF AN ARRAY
An array is a contiguous and homogeneous memory location identified by a name. The access to each location is done through
an index or subscript. Contiguous means the locations (memories) that are continuously next to each other. Homogeneous meaning
the cells can only hold data of the same kind. All the data is of the same type: integer, float, etc. The index is a number
that represents each room, beginning with 0 and ending with a defined maximum value. The index uniquely identifies each cell
allowing access to a corresponding location.
HOW DO YOU DECLARE A VARIABLE ARRAY?
The way to declare an array is the same as declaring other single variables, such as int x, except that the maximum size of
the array must be specified, for example int x[10]. To declare an array, start with the data type, give the array a name,
and specify the maximum size of the array by enclosing the number of elements in brackets. The following line of code illustrates
the above process:
int item[10];
The variable item is declared as an array of 10 locations that each holds an integer value.
ARRAY SIZE AND ITS RANGE
When declaring an array, the size determines the number of memory locations that are reserved for the array. Note that the
index of the array starts at zero rather than one. For example, and array of size ten, the index ranges from zero to nine.
Why zero instead of one? One answer is that the internal memory addresses start from zero. Therefore, the compiler doesn't
need to adjust the conversion of an array to its address. In the following array declaration, note the array’s range
runs from zero (0) to nine (9).
int item[ 10 ]; // Array range of 0 to 9 will access each element of the array. |
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 5-
ARRAY: ARRANGEMENT OF DATA
You may have heard the following expressions: array of flowers, array of thoughts, or an array of soldiers standing by. What
do all these expressions have in common? Each of the above has several alike elements that are arranged in order (one next
to the other). In the world of programming, an array has similar properties that are arranged in the memory cells (locations).
One cell follows another with each holding information of the same kind..
DEFINITION OF AN ARRAY
An array is a contiguous and homogeneous memory location identified by a name. The access to each location is done through
an index or subscript. Contiguous means the locations (memories) that are continuously next to each other. Homogeneous meaning
the cells can only hold data of the same kind. All the data is of the same type: integer, float, etc. The index is a number
that represents each room, beginning with 0 and ending with a defined maximum value. The index uniquely identifies each cell
allowing access to a corresponding location.
HOW DO YOU DECLARE A VARIABLE ARRAY?
The way to declare an array is the same as declaring other single variables, such as int x, except that the maximum size of
the array must be specified, for example int x[10]. To declare an array, start with the data type, give the array a name,
and specify the maximum size of the array by enclosing the number of elements in brackets. The following line of code illustrates
the above process:
int item[10];
The variable item is declared as an array of 10 locations that each holds an integer value.
ARRAY SIZE AND ITS RANGE
When declaring an array, the size determines the number of memory locations that are reserved for the array. Note that the
index of the array starts at zero rather than one. For example, and array of size ten, the index ranges from zero to nine.
Why zero instead of one? One answer is that the internal memory addresses start from zero. Therefore, the compiler doesn't
need to adjust the conversion of an array to its address. In the following array declaration, note the array’s range
runs from zero (0) to nine (9).
int item[ 10 ]; // Array range of 0 to 9 will access each element of the array. |
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 5-
ARRAY: ARRANGEMENT OF DATA
You may have heard the following expressions: array of flowers, array of thoughts, or an array of soldiers standing by. What
do all these expressions have in common? Each of the above has several alike elements that are arranged in order (one next
to the other). In the world of programming, an array has similar properties that are arranged in the memory cells (locations).
One cell follows another with each holding information of the same kind..
DEFINITION OF AN ARRAY
An array is a contiguous and homogeneous memory location identified by a name. The access to each location is done through
an index or subscript. Contiguous means the locations (memories) that are continuously next to each other. Homogeneous meaning
the cells can only hold data of the same kind. All the data is of the same type: integer, float, etc. The index is a number
that represents each room, beginning with 0 and ending with a defined maximum value. The index uniquely identifies each cell
allowing access to a corresponding location.
HOW DO YOU DECLARE A VARIABLE ARRAY?
The way to declare an array is the same as declaring other single variables, such as int x, except that the maximum size of
the array must be specified, for example int x[10]. To declare an array, start with the data type, give the array a name,
and specify the maximum size of the array by enclosing the number of elements in brackets. The following line of code illustrates
the above process:
int item[10];
The variable item is declared as an array of 10 locations that each holds an integer value.
ARRAY SIZE AND ITS RANGE
When declaring an array, the size determines the number of memory locations that are reserved for the array. Note that the
index of the array starts at zero rather than one. For example, and array of size ten, the index ranges from zero to nine.
Why zero instead of one? One answer is that the internal memory addresses start from zero. Therefore, the compiler doesn't
need to adjust the conversion of an array to its address. In the following array declaration, note the array’s range
runs from zero (0) to nine (9).
int item[ 10 ]; // Array range of 0 to 9 will access each element of the array. |
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 8
OBJECT AND CLASS: EVERYTHING AS AN OBJECT OF A CLASS
The world around us is made of objects and each object has its own characteristics as to what it does and what can be done
to it. A group of similar objects can be generated from a model (blueprint) that encompasses essential characteristics such
as its data and its functionality, which is known as class. A class bundles the data, its functions, and how these two members
interact with each other as well as the outside world. Introduction of class and its objects will shift the focus from Procedural
Programming (with function in center) to Object Oriented Programming where security (access), extendibility (expansion), and
reusability (cost) are the major concerns. As a matter of fact, you have already dealt with class and object. The simple
cin and cout statements are objects of the iostream class.
HOW TO MAKE A CLASS
There are two ways to make a class, one that starts with the keyword struct and one that starts with the keyword class itself.
The following examples of employee class describe the similarities and differences between when the keyword class or the keyword
struct is used. Note that the only difference between struct and class in C++ is the default accessibility of the members.
By default members in struct are public, whereas members in class are private. However, you may argue that to define a class
it would be easier to simply use the keyword class instead of using struct as the alternative, thus eliminating much confusion.
C++ has demonstrated its loyalty to C language by extending the existing struct. A C++ programmer prefers class versus struct
since the default accessibility of the members of a class is private.
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
CHAPTER 9
FILE HANDLING: A DATABASE
A key feature of the computer is the ability to store information, and to retrieve it at a later time. The information (data)
has to be saved somewhere, which is called a file, and has to be under a name, which is called a filename. A program constantly
interacts with the files to store, retrieve, modify or delete the data. Traditionally, a file that is used to store or retrieve
data is called a data file or an input file. A data file may contain personal information such as the names of employees,
their telephone numbers and salaries.
You may work interactively with a program and enter the data each time. However, when the input data becomes large, it is
necessary to work with a data file rather than typing the data over and over each time. One example of a data file would be
supermarket pricing, where a huge amount of data is manipulated. In today’s web engine, hundreds of files may have
to be processed in order to complete a search. The advancement of the Internet has proportionally increased the number of
files and their size. For any organization, data processing and data manipulation are essential operations. A database runs
the day-to-day operations by adding new records, searching for particular record(s), modifying the existing records and generating
reports. Due to the real-time demand of data, the efficiency of databases is subject to review and, as a result, a tremendous
effort has been spent to secure their reliability.
WORKING WITH A DATA FILE
In order to work with a data file, whether it is to be used to store data or retrieve data, the following steps need to be
taken into consideration.
1) Include the file stream in the header file section.
2) Associate a name with the data file and specify its mode as to whether to output, append or input. This step will open
the data file and get it ready.
3) Use the associated file name throughout the program the same way cin and cout are used, except that with cin and cout data
are handled by the console (keyboard and screen).
4) Close the file when you are finished.
TO ACCESS A DATA FILE FOR INPUT
To access a data file to input from, the following steps should be considered:
1) Include the file stream header file.
2) Associate an input file name with an input file stream for accessing the data file.
You may indicate explicitly the mode of file access as input:
As a convention, the name fin is used which stands for “file in” as the C++ word cin stands for “console
in”.
3) Use the associated file name to access the data the same way cin accesses the data, e.g. from the keyboard.
4) Close the file indicating that the data access is terminated.
|
Please choose from the following
|
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 10
RECURSION: FUNCTION CALLING ITSELF
Have you ever had a dream that you were dreaming? Have you ever stood in a room with many reflecting mirrors, or have you
ever viewed a landscape and in the distance the image begins to fade? Have you recalled memories back to your childhood?
Have you opened a dictionary to the middle, and then to the middle of the middle to look for a word such as “heuristic”?
All these actions have something in common. Somehow, each action is recurring (calling) itself. There are many problems of
this type that can be solved by reiterating or including the problem as part of the solution. A problem is recursive when
its solution requires continually recalling the original problem. Eventually the problem is broken down to the point where
a direct solution can be reached. Recursive solutions are elegant and natural because the whole problem can usually be expressed
in two statements. A statement that has a direct solution (base solution) is not recursive. While a statement that calls itself
and, with each call, simplifies the problem to the point that the base solution is reached is recursive.
If you are confused as to what recursion is, it will soon become clear. There are many recursive patterns in nature, such
as a rabbit breeding or the growing branches of a tree. Grasping the concept of recursion may require detailed knowledge.
Some simple mathematical examples such as Factorial (n!) or Fibonacci number series can express the concept of recursion clearly.
WORD EXAMPLES OF RECURSION:
Let us look at a recursive problem and try to formulate it in a logical way, so that you can better understand recursion.
Ask yourself this question: “Who are your ancestors?”
“My parents are my ancestors” is one answer, but this does not satisfy the question. Your second answer is “My
parent’s ancestors are my ancestors”. You can see that the solution is recursive because the word ancestor (which
is the problem) is used to define the solution. Together, the two statements (shown below) cover all ancestors. However,
when it comes to a specific problem in a given database, such as “Ancestorof (x,Mary)?” the answer will eventually
end with a non-recursive statement (base solution).
ancestorof(x,y) if parentof(x,y)
ancestorof(x,y) if parentof(x,z) and ancestorof(z,y)
Now look at the following recursion as to who is your boss?
bossof(x,y) if supervises(x,y)
bossof(x,y) if supervises(x,z) and bossof(z,y)
In the above example, which statement is not recursive and which is it? Keep in mind that in order to solve the problem we
need both of the above statements.
MATHEMATICAL EXAMPLES OF RECURSION
The two common examples of recursion are: Factorial (n!) and Fibonacci number series. A Factorial of a number is defined by
the multiplication of that number with the Factorial of its previous number. However, the factorial of zero is defined as
1.
A Fibonacci of a number is the sum of the Fibonacci of the two previous numbers (one before and two before). However, the
first Fibonacci is 1 and the second Fibonacci is 1.
factorial(n) is n * factorial(n-1) if n>0
if n is 0 factorial is 1;
What is the factorial of 4 – factorial(4)?
4! is 4* 3!
where 3! is 3 * 2!
where 2! is 2*1!
where 1! is 1 * 0!
where 0! is 1 (hint: no more recursion)
Now that we found the 0!, we can ladder up and compute 1*1*2*3*4 which is 24. The above structure is known as a “tree
structure”.
|
Please choose from the following
|
|
|
 |
Sample Chapters 11-20
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 11
SORTING: ORDERING IT TO SEARCH FASTER
Can you imagine trying to locate a word in a dictionary that is not sorted or put in order? You would have quite a bit of
difficulty finding the word. Sorting makes searching not only efficient but in many applications possible. How does a computer
sort the data? It is very similar to the way you sort a series of numbers or a deck of cards. There are many ways that the
data can be sorted, therefore many algorithms are there to look into and analyze. Among various existing algorithms one algorithm
may perform better than another one in certain circumstances. While one sort algorithm will do the job of sorting, it is important
to understand various sorting techniques, trends and circumstances so that a proper algorithm can be chosen. The complexity
of a sorting algorithm is measured in terms of speed (time), amount of space required for memory storage and/or its simplicity.
The three categories of sorting techniques include exchange sort, selection sort and insertion sort. These categories are
based on the movement and exchange of the two next items (exchange), selecting the next item (selection), and inserting the
next item in the right position (insertion). In most of the sorting techniques, the unsorted data is already placed in an
array and the same array is used to hold the sorted data so as not to waste memory. There are cases where an array is not
used. The data may be stored in the files or even in some other data structure such as a linked list built by pointers.
SORT IT YOURSELF: DO IT YOUR WAY
Imagine that there are 10 cards sitting next to each other on your desk and your task is to put them in order (sort it) from
smallest to largest (ascending order). You manage to do it right away. How did you do that? Now, try to write down each step
as you did the sort. Did you continuously compare each card with the next card and then exchange (swap) the cards? If not,
did you pick up the smallest card and place it at the beginning? Or did you place each card in its spot as you performed the
sort? If you didn’t follow any of above, then what did you do? Did you follow the same steps over and over? If I ask
you to do it over would you be able to perform the same task? Be aware that others may have different approaches than you
have in sorting the cards. No matter how the intermediate work is done the result should be the same- data is sorted. However
one thing is common to every one. Data is scanned over and over. This is why we need a systematic approach to programming.
Now let’s consider what would have happened if all ten cards were already sorted except one card? While there are different
techniques to sort a list of data, one technique may be preferable due to circumstances. This is why consideration of the
three sorting approaches (exchange, selection, insertion) may be helpful.
SORT ASCENDING OR DESCENDING
Data can be sorted in ascending or increasing order from smallest to largest. Alternatively data can be arranged in descending
(decreasing) order from largest to smallest. Notice data can be numeric, alphabetic, or alphanumeric, such as:
111 678 999 1234
A M X a x
BYE GOOD HELLO
123BYT G482KR xyzcabbies
When the data is not numeric, two items are compared in terms of their ASCII character values. Remember, the ASCII value for
‘0’ is 48, A is 65, and lower ‘a’ is 97.
EXCHANGE SORTS
In order to sort a series of items, two items at a time are compared, if they are not in order (for example the first item
is greater than second item) they are exchanged. However, if these two items are already in order, the exchange will not take
place. After the comparison is completed, a conclusion can be drawn that the second item is not the smaller one. Then the
next two items are compared and so forth. For each comparison, there would be the possibility of an exchange. You may have
wondered why this family of sorting is called exchange sort. Among the family of exchange sorts are bubble sorts and shell
sorts. Bubble sorts compare two adjacent cells (items) while shell sorts compare elements with a distance of more than 1.
By the time entire array is scanned, we can conclude that the largest element is placed at the end of the array (alternatively,
the smallest item finds itself at the beginning of the array).
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 12
SEARCHING: TO LOOK AND TO FIND
The computer was invented to perform complex mathematical computations, however this trend has changed and the computer has
become more of a searching machine (engine). Non-stop, this machine looks to find proper matches, travel destinations, inventories,
personal files, or even previous computations. In fact, searching is the center of most computer applications and increasingly
dominates all aspects of our home, school, and office applications. Many algorithms have been developed to perform these
searches, however, some searching algorithms are easy, some are difficult, and some are faster than others. Among the searching
algorithms we can name sequential (linear) search, binary search and hashing. Each of these searches has their own advantages
and disadvantages. One can argue that, with the high speed and memory size of today’s computer, linear search would
be sufficient for relatively small data sets. But, as the amount of data overwhelmingly increases, there is as need to explore
alternative algorithms for searching. Hashing performs best in certain situations in comparison to other searching algorithms.
Another efficient searching algorithm is known as search tree built on a data structure called tree. The data on a tree is
stored in a fashion representing the branches of a tree and a root, interestingly it should be viewed upside down. The tree-searching
algorithm can be difficult to understand and program. Understanding and analyzing various searching techniques using criteria
such as consumption of computer time and/or space enables one to choose and decide on a proper search technique.
SEARCH PROGRAM STEPS
Every search program consists of the following three major steps.
1. Interaction
2. Look at existing information
3. Responding back
In the interaction step, the program asks the user to enter a proper request; and user responds by inputting the data, usually
through the keyboard. In the second step, the program will take the requested information (search key) and search through
existing information that is stored in a file, array, memory location, or any other data structures. The program then responds
back to say whether or not the information was found.
SEARCH EXAMPLES
The following list is some of the search examples:
1. Computer user name and password
2. ATM and account validation
3. Grocery shopping
4. IRS or governments inquiries
5. School administration, Motor vehicle Dept.
6. Entire search engines, etc.
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 13
ADDRESS, POINTER VARIABLE,
DYNAMIC MEMORY ALLOCATION
A computer’s memory is divided into slots. Each slot has an address that can hold a value. A memory that holds a value
and has the ability to change it when necessary is known as a variable. There are variables that hold values such as integers,
characters, or other data types. A variable that holds an address of another variable is known as a pointer variable or simply
as a pointer. Pointers provide open access to memory addresses and are beneficial to programmers, but pointers can put the
security of a system at risk. For this reason, pointers are a controversial topic. The storage for pointer variables can
be allocated during run time (dynamic allocation), as the program requires the memory. The memory for a dynamically allocated
variable can be freed after its usage. This allows availability of the storage for other variables. The allocation and de-allocation
of memory leads to a great saving of computer memory and a programmer can build their own data structures and manipulate them
as desired. Furthermore, this provides other alternatives in building data structures.
ADDRESS OF A VARIABLE
Every variable has an address and a value. Normally when a variable is declared, an address is assigned to the variable by
the system (compiler). The address of a variable is accessed by an ampersand &; it is known as an address operator.
A POINTER VARIABLE
A regular variable holds a value such as an integer. A pointer variable, or simply a pointer, holds a value as well but its
value is the address of another variable. Through this address, the value of the variable can be accessed. In other words,
a pointer can indirectly access the value of the variable. An asterisk (*) before the variable name is used to declare a pointer
variable.
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 14
DATA STRUCTURES
Data structures is about how data is organized, structured, and stored in memory, as well as how this data is retrieved and
manipulated. Since computer programming began, many data structures have been developed, each having its own name, properties,
and characteristics. Understanding the existing data structures enables a programmer to choose the proper data structures
to solve a problem. The programmer has to decide if what has to be done can be accomplished by reusing or modifying existing
data structures, rather than reinventing the wheel. Let us start this way, in building a program a piece of data does not
stand-alone and there is a major concern as to how the data are related to each other in a program. For each kind of relationship,
there is a predefined structure, which conceptually (abstraction) or functionally (implementation), expresses how the data
is stored, retrieved, or manipulated. Data can be structured as an array, struct, or a file; and these are the first data
structures that programmers are exposed to. However, talking about data structures is more about major concepts such as stacks,
queues, trees, hashing, sets, and graphs. The understanding of different data structures enables the programmer to solve a
problem efficiently (time and space), such as applying and/or reusing the existing, tested algorithms. A large library of
algorithms for data structure usage has existed for many years and still developing new algorithms, or optimizations of the
existing ones, is a major topic of advanced computing. Let’s put it this way, in the field of computer science there
are a series of important algorithms for solving certain problems, each having its own method of organizing data so that variables
(objects) are created; this way of creating objects is known as data structures. You will observe that algorithms and data
structures are very closely related and, in fact, a program is created by the combination of algorithms and data structures.
In many occasions, as soon as the choice for the data structure is made, the rest of the program will easily follow. The storage
for a data structures could be allocated during compile time- static data structures or during run time – dynamic data
structures. The major data structures are stacks, queues, trees and graphs. However, each of these data structures can be
implemented either statically, for example by arrays, or dynamically by linked lists. There are trade-offs in selecting a
static data structure versus a dynamic data structure that will be discussed in detail.
DATA STRUCTURE IMPLEMENTATION: STATIC VERSUS DYNAMIC
There are two ways data structures can be implemented (built), statically and dynamically. The memory for static data structures
is of a fixed size and is allocated during the compilation time, meaning that the size of the array or structure is known
in advance. In dynamic data structures, the size of the data structure grows and shrinks; meaning memory space is allocated
during the execution time. In dynamic data structures, an array may be built one by one. There are advantages and disadvantages
in choosing either static or dynamic data structures. It all depends on the situation and the problem. That is why the study
of data structures becomes important. Again, note that the static data structures are implemented by fixed sized arrays, and
dynamic data structures are built with pointers and dynamic allocation of memory.
ADVANTAGES OF STATIC DATA STRUCTURES
Faster: The memory for static data is allocated during the compilation time, which makes the program run faster rather than
if it had to stop and allocate the required memory each time. An array index can randomly access any element of an array.
Easier to understand: It is easier to define and to use a static data structure rather than its counter part dynamic data
structure.
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 15
POLYMORPHISM, TEMPLATE, AND ADT
Polymorphism consists of two words: poly, which means “many,” and morph, which means “form.” In programming,
polymorphism is the ability to have many forms for the same name. An example of polymorphism is when different functions
do a similar task and have the same function name or similarly when using many forms for the same operator. Polymorphism,
encapsulation, and inheritance are three important features of object-oriented programming. Function overloading and operator
overloading are two examples of polymorphism. A user function or a built-in operator can be overloaded while performing what
it was originally designated to do. A computer teacher can become overloaded by teaching an additional math or other course.
One form of polymorphism is function overloading. For example, the same function name: print( ) prints the list of items
in a queue or a stack, regardless if they were created statically or dynamically. Another example of polymorphism is operator
overloading which adds a new meaning to most of the C++ operators. C++ operators are defined for the basic data types; with
operation overloading, the same operators can be applied to user-defined types, keeping the operation in the same form as
it is applied to the basic types. The goal of operator overloading is to allow user defined types (classes) to behave in the
same way as built-in types. Polymorphism contributes to the concept of abstraction by providing a meaningful name that can
be used differently for several similar functions and operations. Therefore, a programmer can focus on the function’s
and operator’s work rather than getting involved in the overwhelming details of the implementation. As long as the same
interface is exposed, the implementation is irrelevant. Finally, for a language to be considered an object-programming language,
it must support the features of polymorphism. C++ templates allow programmers to code and reuse code regardless of the specific
data type. When the type of data is defined, the compiler will generate the code as if it was written for that specific data
type.
FUNCTION OVERLOADING
A function is overloaded when the same function name is used to perform different tasks depending on the data type. Function
overloading is one of the simplest forms of polymorphism. In the following program, there are three versions of findsmaller(
); each version of the function takes and returns a different data type. The function findsmaller( ) is referred to as an
overloaded function. Without the use of function overloading, the same program would require three different function names
to perform the same task.
HOW DOES FUNCTION OVERLOADING WORK: FUNCTION SIGNATURE
How does the compiler determine which function to call when there are several functions with the same name? A C++ complier
uses the function’s signature to determine which function to call. A function’s signature consists of the function
name and the parameter (argument) list. Note that in the function’s signature, the return type is not needed because
it is necessary in the function’s prototype. If there is not an exact match in the argument list, the C++ compiler tries
to use a standard type conversion such as converting an integer to a double if necessary. The following program swaps different
data types; the compiler is able to figure out the correct function call by using the actual types from the arguments. The
number of the arguments and their type may vary in each function.
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 16
INHERITANCE:
REUSABILITY AND EXTENDABILITY
The world around us is made of objects that share many similarities. These similarities can be classified into common groups.
For example, in biology taxonomy organisms are classified into a hierarchy of group, from general to specific. In C++, objects
are created from classes; and a class may share (inherit) some common data members and member functions that belong to another
class or classes. As a result, a new class can be created based on an existing class rather than creating it from scratch.
An inherited class can have its own data and function members and can modify or override the inherited members. Inheritance
is an important tool of Object-Oriented Programming (OOP), because it promotes reusability and ease of extensibility by building
on what is already there and customizing it as desired. A programmer can build a hierarchy that goes from a general class
to a specific class by incorporating inheritance. With class hierarchy a program is easier to follow, debug, and modify. With
inheritance, a class is built on an existing class that has already been tested; therefore, inheritance reduces the time and
the cost of development as well as minimizes errors in the program. Inheritance is also known as derivation or specialization.
In fact, inheritance is not something new. For example, humans have organized knowledge into hierarchical structures such
as the animal kingdoms.
CLASS INHERITANCE: GENERAL SYNTAX
The general form of a class inherited from another class is shown in fig 9.1. The access specifier (access control) can be
public, private or protected. The syntax for class inheritance is the same as a regular class except that after the class
name (derivedname) there is a single colon, the derivation access type (accessspecifier), and the name of the class (baseclassname)
from which it is derived.
class derivedname : accessspecifier baseclassname{
accessspecifier: memberdata;
accessspecifier: memberfunctions; };
Figure 16.1 – Class inheritance syntax
EXAMPLE OF INHERITANCE
Take a moment and categorize yourself as an object. For example, are you a full time employee, a part time student, or both?
Do you have a bank account? Do you own a car? As human beings we categorize the objects around us into hierarchical structures.
For example, livings things are divided into five kingdoms (plant, animal, fungi, etc.). Furthermore, these kingdoms are divided
into smaller subcategories. Humans belong to the kingdom Animilia, the phylum Chordata, and the class Mammilia. These classes
all share some commonality such as attributes (data) and behaviors (functions) that can be factored out.
EMPLOYEE CLASS: An employee can belong to a base class of person and several derived classes such as a salaried or hourly
paid class both of which inherit from the person class. An employee can be full time or part time. Moreover, an employee can
be a consultant, manager, or executive.
STUDENT CLASS: There may be different kinds of students in a college that all share common characteristics.
The student class is the base class and students can be further categorized into the following classes:
Undergraduate
Graduate
Full time
Part time
Freshman, sophomore, junior, senior
Exchange
International student
For example, Jane Doe is a part time, freshman, undergraduate, exchange student.
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 17
CHARACTER MANIPULATIONS, STRING CLASS, AND IOSTREAM
Each strike or multiple strikes on the keyboard represents a character: a letter, a digit, or a symbol. However, some characters
are not labeled on the keyboard and some of them are not printable. Each character is represented by a numeric code that was
agreed upon and standardized by a committee and this is known as ASCII code. Characters are the building blocks of any data
in a computer, whether they are integers, doubles, or strings. In fact, one of the first jobs of a system programmer is to
convert a sequence of characters to its intended meaning. For example, 1, 2, and 3 (one, two, three) becomes 123 (one hundred
twenty three). Similarly, a sequence of characters represents a word, several words form a sentence, and a combination of
sentences generates a story.
A C–style string is an array of characters that terminates with a null as its last element. While you can initialize
an array to a constant string such as char name[]=”ebrahimi”, you cannot treat the string as other built-in types
such as int or double by using = for assignment or comparison (relational) operators such as > between two strings. Library
functions strcpy( ) and strncpy( ) are used to copy (assign) one string to another. Similarly, library functions strcmp( )
and strncmp( ) are used to compare two strings for equality, less than or greater than. Originally in C, string-handling
functions were introduced in string.h and later on in C++, in cstring, include directive (header file). Upon the introduction
of string as STL in 1994, strings are now treated as other basic data types as a class with many more capabilities. String
class provides a rich set of members for string manipulation that surpasses the traditional C-style null-terminated string.
However, let us not forget that when it comes to speed, some of the C-style functions supersede the functions of string class.
With the string class, operations are done in the same way as other operation on integer or float data types. Since string
class is a STL container, many other components like iterators and algorithms work and makes string manipulation and pattern
matching easier because you don’t have to built the function from scratch.
STRIPPING THE WHITE SPACE WITH CONSOLE INPUT - cin
White space is considered a space, a tab, a vertical tab, or a new line. When receiving input using cin (an object of istream,
which is also known as console input), the leading white space to an input is ignored. In several situations, ignoring white
space is useful, but there are cases where white space is part of the data, such as a street address, where we do not want
to break the address into separate units. One solution is to replace the white space with punctuation such as a dot (.) as
demonstrated by the program below. Additional characters to replace blank spaces can be cumbersome; you may argue that this
is not a desirable solution and wish to know an alternative.
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 18
STANDARD TEMPLATE LIBRARY
WHY STL (STANDARD TEMPLATE LIBRARY)?
There are common data structures and algorithms that are used over and over in programs. C++ provides ready-made solutions
for these data structures and algorithms by including them in a library. Therefore, a programmer can simply use them rather
than make them. The advantage is that the programmer can use these data structures and algorithms that are defined, standardized,
tested, and ready to be used rather than starting from scratch each time. In addition to the original built-in functions
of C/C++, in 1994 STL became part of the standard library by adding new classes that work with any data type, promoting reuse
rather than reinventing the wheel. Certain data structures and algorithms are used over and over by programmers, so why not
automate these data structures and algorithms? Certain components of STL are better suited for different circumstances.
For beginners or even experienced programmers STL can be difficult to grasp. The syntax of STL is a little intimidating.
After observing the capabilities of STL, the value of this tool becomes obvious and you want to use it more. Just keep in
mind that the goal of STL is to provide you with a collection of generic tools so that you can enhance your programmability.
If you have had difficulty building a linked list and operating it manually, using STL you can request an automatic double
linked list with the all the necessary functions to operate it. Just remember STL by itself is a vast topic and you need time
to become acquainted with it.
THREE COMPONENTS OF STL: CONTAINERS, ALGORITHMS, AND ITERATORS
STL comes with three components that work with each other to solve problems of all different kinds. These three components
are known as containers, iterators, and algorithms. As the name suggests, a container represents storage units that hold data
elements (data structure). An iterator is like a loop that moves and scans through the container. An iterator that points
to the contents of a container can be used to traverse through the elements of that container. Each container has its own
algorithms (functions); there are also algorithms that work with all containers. In summary, the algorithms are the programs
(functions) that are applied to data structures.
CONTAINER TYPES
Containers can be divided into two parts: sequence containers and associative containers. Sequence containers are: vector,
list, and deque (double-ended queue). Associative containers are sets and maps. From sequence containers other containers
have been created, such as stacks and queues, which are known as adapters.
STL ITERATORS
The main job of STL iterators is to access the elements of a container. The word iterator reminds one of a loop or iteration;
however, iterators are more like pointers than loops. Some see STL iterators as smart pointers. Iterators are an abstraction
of pointers. An iterater points to a container and the iterator can be incremented, decremented, and checked for equality
(= =, !=) in the same way as a pointer pointing to an element of an array. The content of what an iterator points to can be
accessed with * indirection operator (*iter) or (*iter).first for the map and set (or alternatively iter ->first). The functions
begin( ) and end( ) return iterators than can be used to access the beginning of the container and the terminating end of
the container. Iterators are the bridge between algorithms and containers. Containers may have specified iterators. In addition
to traversing the data elements of a container, there are two kinds of iterators that are connected to the input/output streams
known as input iterator (inputIterator) and output iterator (outputIterator). These iterators allow you to copy the contents
directly to the output device or access the data from the input device and copy it to the container.
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 19
ERRORS, EXCEPTION HANDLING, AND SOFTWARE ENGINEERING
While your program is running, you may encounter a problem that is unexpected. This problem can bring down the whole system.
For example, your program may want to access a file that does not exist or, is in another directory. What would happen if
your program is computing the average of a series of numbers, but the counter (denominator) is zero or becomes zero, or what
happens to your program when it requests more memory than compiler can provide? Obviously these are unexpected situations
that rarely happen and if they occur in an unguarded program, they may cause severe consequences. The strategy to handle errors
is to provide a systematic way of detecting them and take the necessary actions to fix them and recover the program.
You may have already taken proper measures to combat the errors in your program simply by using an if-statement accompanied
by a display message. The introduction of the assert( ) function from header #include is more advanced and takes
advantage of the system error messages and aborts the program upon an unwanted situation. One might argue that the assert(
) function will not be able to recover from the bug. Rather than aborting the program, you can take a different action when
the bug occurs. A more sophisticated and systematic approach for error handling is known as exception handling that was introduced
by ANSI-C++ standard and added to C++. It is called an exception since it is unlikely to happen, but when it does happen it
may produce unwanted results. Exception handling consists of enclosing the code that may result in an exception in a try block
and if an exception occurs it is thrown. The statement that handles the exception is inside the catch block. After an exception
is thrown (raised), normal control flow will suspend and the program will search for a match or a portion of the program that
can handle the exception. After the exception is handled the program will either terminate or resume normal execution after
the corresponding catch block.
Use of exception handling can separate error reporting from error handling and as a result handling errors becomes systematic
and readable.
In conclusion, use of exception handling does not guarantee that errors will not occur. There is no guaranteed solution in
preventing errors. One should consider having a fault tolerance system.
CATEGORIES OF BUGS
Programming bugs (errors) can be categorized into three kinds: compile time, run time, and logical errors. Syntax or compile
time errors are known as grammatical errors that are detected by the compiler. Examples of syntax errors are misspelling the
keywords, omitting the necessary punctuation such as a semicolon, or not balancing the quotation, parenthesis, or statement
pairs. Run-time errors are errors that occur during the execution of the program when it attempts to perform an operation
that the system cannot perform (illegal). A popular example of a run-time error is when a program tries to divide a number
by zero. Logical errors produce the wrong output, which is caused by applying inappropriate algorithms; for example when
subtraction is used instead of addition. One analogy of a logical error would be driving east when intending to go west,
and the driver will never reach the desired destination if given the wrong directions. Remember, in order for a program to
produce output, the program has passed the stage of syntax and run-time error checking. Logical errors are the most difficult
to detect and they are often confused with run-time errors. If there is a run-time error, the system will terminate or an
exception will take place. Linkage errors might result when linking two separately compiled programs (functions). Duplication
of variable names is an example of a linkage error. There are different opinions as to what is considered a logical error
and what is not. Errors can be categorized with respect to the compiler as follows: lexical errors, such errors resulting
from misspelling; syntactic errors, such as unbalanced quotations or parentheses; semantic errors, such as applying an arithmetic
operator to incompatible variables (data types), and logical errors, such as calling a recursive function without an exit
(infinite).
|
Please choose from the following
|
Dr. Ebrahimi's C++
Programing Easy Ways
Providing simple ways of learning C++ with a
trusted source and materials
|
Please choose from the following
|
CHAPTER 20
POTPOURRI (MIXED BAG)
While wrapping up this book, I found there were many concepts and topics that should have been introduced in earlier chapters
but did not fit into a single chapter. These topics are introduced here as a mixed bag with a variety of flavors. Also, I
want to congratulate you for getting this far and covering the many chapters. Obviously you have obtained a unique and worthwhile
experience. You should be proud and put into use what you have learned. In my own experience, I have found that repetition
is the key to my own learning, whether learning a programming language or a natural language like Spanish or even Chinese.
BIT-WISE OPERATIONS
One power of C/C++ is the ability to perform low-level operations that are done by machine languages. These operations are
performed on bits. Recall, numbers and addresses are represented in binary form internally. In many applications, especially
hardware, it is desirable to work with these bits. The language of C/C++ is known as a language that works closely with hardware.
Because of the importance of bit-wise operations, C/C++ chooses to use one key strike for bit-wise operators (&, |) and two
strikes for the logical operators (&&, ||). The following symbols are used for the C/C++ bit-wise operations.
| bit-wise or operator
& bit-wise and operator
^ bit-wise exclusive or operator
<< shift left operator
>> shift right operator
~ bit complement (unary operator)
BIT-WISE OPERATIONS: EXAMPLES
The general form of the bit-wise or operation is variable1 | variable2 where each variable of type integer is converted to
binary (bits). The bit-wise or operation of two bits is zero if both corresponding bits are zero (0), otherwise the resulting
bit is one (1).
The general form of the bit-wise and (&) is variable1 & variable2, where each variable of type integer is converted to binary.
The bit-wise and operation of two bits is one if the two corresponding bits have values of 1, otherwise the resulting bit
is zero.
The general form of the bit-wise exclusive or (^) operation is variable1 ^ variable2, where both variables and resulting variable
are of type integer and are converted to binary. The exclusive or of two bits is zero if the two bits are the same, otherwise
it is one. The exclusive or is different from the bit-wise or in that the exclusive or of two bits with values 1 results to
zero.
The & operator is often used to mask off certain bits, e.g. value & 1111111. The result sets all of the bits of the value
to zero except the first 8 bits (low-order).
In the following program, the binary representation for 3 is 011 and 5 is 101. The resulting bit-wise or is 111 which is 7,
the resulting bit-wise and is 001 which is 1, and the resulting exclusive or is 110 which is 6.
|
Please choose from the following
|
|
 |
|
|