Professional Documents
Culture Documents
CompProgramming2 Ayman
CompProgramming2 Ayman
Level 3
2021-2022
رؤيــة الكليــة
Table of Contents
Chapter 2: Functions............................................................. 17
2.1 What is a Function ........................................ 17
2.2 Function Declaration ..................................... 17
2.3 Function Calling ............................................ 19
2.4 Scope of Variables ......................................... 25
2.5 Functions with no Return Types ..................... 26
2.6 Passing Arguments to Functions...................... 29
2.7 Parameters Default Values ............................. 32
2.8 Overloaded Functions .................................... 34
2.9 Prototyping Functions .................................... 36
2.10 Recursion ..................................................... 40
i
Table of Contents
ii
Table of Contents
iii
Table of Contents
iv
Chapter 1: Basic Concepts of C++. _____________________________________
Chapter 1
1.1 Introduction
___________________________________________________________
2
Chapter 1: Basic Concepts of C++. _____________________________________
Header Part:
Directives (Ex: #include <filename>)
Prototypes (related to functions if they coded after they called)
Global Declaration (Global variables to all functions )
Block:
The block is a function.
Any C++ program may have many functions but at least
one function called main() in the form:
void main()
{
Variables Declaration;
STATEMENTS;
return;
}
#include <iostream>
using namespace std;
int main ()
{
cout << "My First Program"; // print My First Program
return 0;
}
My First Program
___________________________________________________________
3
Chapter 1: Basic Concepts of C++. _____________________________________
#include <iostream>
int main ()
___________________________________________________________
4
Chapter 1: Basic Concepts of C++. _____________________________________
return 0;
// and /*……*/
// line comment
/* block comment */
___________________________________________________________
6
Chapter 1: Basic Concepts of C++. _____________________________________
Data_type Variable_name;
For example:
int a;
float number;
___________________________________________________________
7
Chapter 1: Basic Concepts of C++. _____________________________________
int age;
cin >> age;
___________________________________________________________
8
Chapter 1: Basic Concepts of C++. _____________________________________
1.5.1 If statement
if (x == 100) if (x == 100)
cout << "x is 100"; {
cout << "x is ";
cout << x;
}
___________________________________________________________
9
Chapter 1: Basic Concepts of C++. _____________________________________
if (condition) if (condition)
statement 1; {
else statement 1;
statement 2; ……
statement n;
}
else
{
statement n+1;
……
statement m;
}
For example:
if (x == 100)
cout << "x is 100";
else
cout << "x is not 100";
___________________________________________________________
10
Chapter 1: Basic Concepts of C++. _____________________________________
if (condition_1)
if (condition_2)
statement_1;
else
statement_1;
switch (expression)
{
case 1:
group of statements 1;
break;
case 2:
group of statements 2;
break;
……….
default:
default group of statements;
}
For example:
switch (x)
{
case 1: cout << "x is 1";
break;
case 2: cout << "x is 2";
break;
case 3: cout << "x is 3";
break;
___________________________________________________________
11
Chapter 1: Basic Concepts of C++. _____________________________________
default:
cout << "x is not 1, 2 nor 3";
}
#include <iostream>
using namespace std;
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
}
cout << "FIRE!";
___________________________________________________________
12
Chapter 1: Basic Concepts of C++. _____________________________________
return 0;
}
10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
while (condition)
#include <iostream.h>
int main ()
{
int n;
cout << "Enter the starting number>";
cin >> n;
while (n>0)
{
cout << n << ", ";
--n;
}
cout << "FIRE!";
return 0;
}
___________________________________________________________
13
Chapter 1: Basic Concepts of C++. _____________________________________
do
{
statement or block of statements;
}
while (condition);
#include <iostream>
using namespace std;
int main ()
{
unsigned long n;
do
{
cout <<"Enter number (0 to end):";
cin >> n;
cout << "You entered:" << n <<"\n";
}
while (n != 0);
return 0;
}
___________________________________________________________
14
Chapter 1: Basic Concepts of C++. _____________________________________
Using break we can leave a loop even if the condition for its
end is not fulfilled. It can be used to end an infinite loop, or
to force it to end before its natural end. For example, the
following program stops the count down before its natural
end:
#include <iostream>
using namespace std;
int main ()
{
int n;
for (n=10; n>0; n--)
{
cout << n << ", ";
if (n==3)
{
cout << "countdown aborted!";
break;
}
}
return 0;
}
10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
___________________________________________________________
15
Chapter 1: Basic Concepts of C++. _____________________________________
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)
{
if (n==5) continue;
cout << n << ", ";
}
cout << "FIRE!";
return 0;
}
10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
1.8 Summary
Functions
where:
For example:
int Fac(int num); /* Declaration of Fac with one argument*/
___________________________________________________________
18
Chapter 2. Functions. ____________________________________________
// function example
#include <iostream>
using namespace std;
int main ()
{
int z;
___________________________________________________________
19
Chapter 2. Functions. ____________________________________________
z = addition (5,3);
cout << "The result is " << z;
return 0;
}
The result is 8
At the point where the function is called from the function main,
the execution control is lost by main and passed to the function
addition. The values passed in the call (5 and 3) are copied to
the local variables int a and int b within the function.
___________________________________________________________
20
Chapter 2. Functions. ____________________________________________
return (r);
// function example
#include <iostream>
using namespace std;
int main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is" << z << '\n';
cout << "The second result is "
<< subtraction (7,2) << '\n';
cout << "The third result is "
<< subtraction (x,y) << '\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is" <<z<< '\n';
return 0;
}
___________________________________________________________
22
Chapter 2. Functions. ____________________________________________
z = subtraction (7,2);
cout << "The first result is " << z;
If we replace the function call by the value that it returns (i.e., 5),
we would have:
z = 5;
cout << "The first result is " << z;
has the same result as the previous call, but in this case we made
the call to subtraction directly as an insertion parameter for the
___________________________________________________________
23
Chapter 2. Functions. ____________________________________________
The fourth case is more of the same. Simply note that instead of:
z = 4 + subtraction (x,y);
z = subtraction (x,y) + 4;
with exactly the same result. I have switched places so you can
see that the semicolon sign (;) goes at the end of the whole
statement. It does not necessarily have to go right after the
___________________________________________________________
24
Chapter 2. Functions. ____________________________________________
z = 4 + 2;
z = 2 + 4;
___________________________________________________________
25
Chapter 2. Functions. ____________________________________________
___________________________________________________________
26
Chapter 2. Functions. ____________________________________________
you will see that the function declaration begins with a type, that
is the type of the data that will be returned by the function with
the return statement. But what if we want to return no value?
#include <iostream>
using namespace std;
void printmessage ()
{
cout << "I'm a function!";
}
int main ()
{
printmessage ();
return 0;
}
I'm a function!
___________________________________________________________
27
Chapter 2. Functions. ____________________________________________
What you must always aware is that the format for calling a
function includes specifying its name and enclosing its parameters
between parentheses. The non-existence of parameters does not
exempt us from the obligation to write the parentheses. For that
reason the call to printmessage is:
printmessage ();
printmessage;
___________________________________________________________
28
Chapter 2. Functions. ____________________________________________
What we did in this case was that calling the function addition
and passing the values of x and y, i.e. 5 and 3 respectively, but
not the variables x and y themselves.
This way, when the function addition is called, the value of its
local variables a and b become 5 and 3 respectively. But, any
modification to either a or b within the function addition will not
have any effect in the values of x and y outside it. This is because
variables x and y were not themselves passed to the function, but
only copies of their values at the moment the function was called.
___________________________________________________________
29
Chapter 2. Functions. ____________________________________________
#include <iostream>
using namespace std;
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
The first thing that should be noted here is that, in the declaration
of the function duplicate, the type of each parameter was
followed by an ampersand sign (&). This ampersand is what
specifies that their corresponding arguments are to be passed by
reference instead of by value as usual.
is changed as:
i.e., without the ampersand signs (&), we would have not passed
the variables by reference, but a copy of their values instead, and
therefore, the output on screen of the program would have been
the values of x, y and z without having been modified.
___________________________________________________________
31
Chapter 2. Functions. ____________________________________________
#include <iostream>
using namespace std;
int main ()
{
int x=100, y, z;
prevnext (x, y, z);
cout <<"Previous=" << y <<", Next=" <<z;
return 0;
}
Previous=99, Next=101
___________________________________________________________
32
Chapter 2. Functions. ____________________________________________
#include <iostream>
using namespace std;
int main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
return 0;
}
6
5
As we can see in the body of the program, there are two calls to
function divide. In the first one:
divide (12)
divide (20,4)
There are two parameters, so the default value for b (int b=2) is
ignored and b takes the value passed as argument, that is 4,
making the result returned equal to 5 (20/4).
In C++, two different functions can have the same name if their
parameter types or number are different. This means that you can
give the same name to more than one function if they have either
a different number of parameters or different types in their
parameters.
// overloaded function
#include <iostream>
using namespace std;
int main ()
{
int x=5, y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
cout << "\n";
cout << operate (n,m);
cout << "\n";
return 0;
}
10
2.5
In the above example, the two arguments passed by the first call
are of type int, therefore, the function with the first prototype is
called. This function returns the result of multiplying both
parameters. While the second call passes two arguments of type
float, so the function with the second prototype is called. This
___________________________________________________________
35
Chapter 2. Functions. ____________________________________________
Until now, we have defined all of the functions before the first
appearance of calls to them in the source code. These calls were
generally in the function main which we have always left at the
end of the source code. But if you try to repeat some of the
examples of functions described so far, but placing the function
main before any of the other functions that were called from
within it, you will most likely obtain compiling errors. The reason is
that to be able to call a function, it must be declared in some
earlier point of the code, like we have done in all the above
examples.
The prototype does not include the body of the function itself
(i.e., the function statements that are enclosed in braces { },
as in the normal definitions).
The prototype declaration ends with a semicolon (;).
The parameter enumeration does not need to include the
identifiers, but only the data type. The inclusion of a name
for each parameter as in the function definition is optional in
the prototype declaration. For example, we can declare a
function called protofunction with two int parameters with
any of the following declarations:
int main ()
{
int i;
do
{
cout << "Type a number:(0 to exit)";
cin >> i;
odd (i);
} while (i!=0);
return 0;
}
___________________________________________________________
38
Chapter 2. Functions. ____________________________________________
The first things that we see are the declaration of functions odd
and even:
This allows the functions to be used before they are defined, for
example, in main, which now is located where some people find it
to be a more logical place for the start of a program: the
beginning of the source code.
Anyway, the reason why this program needs at least one of the
two functions to be declared before it is defined is that in odd
there is a call to even and in even there is a call to odd. If none of
the two functions had been previously declared, a compilation
error would happen, since either odd would not be visible from
even (because it has still not been declared), or even would not
be visible from odd (for the same reason).
___________________________________________________________
39
Chapter 2. Functions. ____________________________________________
2.10 Recursion
5! = 5 * 4 * 3 * 2 * 1 = 120
// factorial calculator
#include <iostream>
using namespace std;
___________________________________________________________
40
Chapter 2. Functions. ____________________________________________
return (1);
}
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " << factorial (number);
return 0;
}
___________________________________________________________
41
Chapter 3
3.1 Structures
struct struct_name
{
member_type1 member_name1;
member_type2 member_name2;
member_type3 member_name3;
… …
… ...
};
struct Example
{
int x;
char y;
};
struct product
{
int model;
int weight;
float price;
} ;
product apple;
product banana, melon;
___________________________________________________________
45
Chapter 3. Structures and Arrays. ____________________________________
Note that, right at the end of the struct declaration, and before
the ending semicolon, we can use an optional field to directly
declare objects of the structure type. For example, we can also
declare the structure objects apple, banana and melon directly
at the moment we define the structure data type, as follows:
struct product
{
int model;
int weight;
float price;
} apple, banana, melon;
___________________________________________________________
46
Chapter 3. Structures and Arrays. ____________________________________
apple.model = 1044;
apple.weight = 100;
apple.price = 50;
Each one of these has the data type corresponding to the member
they refer to: apple.model, banana.model, melon.model
apple.weight, banana.weight and melon.weight are of type int,
while apple.price, banana.price and melon.price are of type float.
struct database
{
int id_number;
int age;
float salary;
};
___________________________________________________________
47
Chapter 3. Structures and Arrays. ____________________________________
int main()
{
database employee; //employee is a structure
employee.id_number=10;
employee.age=28;
employee.salary=500.75;
cout << employee.id_number << " "
<< employee.age << " "
<< employee.salary<<endl;
return 0;
}
___________________________________________________________
48
Chapter 3. Structures and Arrays. ____________________________________
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct movies_t
{
string title;
int year;
} mine, yours;
int main ()
{
string mystr;
___________________________________________________________
49
Chapter 3. Structures and Arrays. ____________________________________
The objects mine and yours can also be treated as valid variables
of type movies_t, for example we have passed them to the
function printmovie as we would have done with regular
variables. Therefore, one of the most important advantages of
data structures is that we can either refer to their members
individually or to the entire structure as a block with only one
identifier.
___________________________________________________________
50
Chapter 3. Structures and Arrays. ____________________________________
#include <iostream>
using namespace std;
sturct Tel
{
int Fix;
int mobile;
};
struct Friend
{
char name[10];
int birth;
Tel phone;
};
int main()
{
Friend Friends;
Friends.name = {A, h, m, e, d};
Friends.birth = 1990;
Friends.Phone.Fix = 2222222;
Friends.Phone.Mobile = 0102020200;
// ..complete the rest of the program
return 0;
}
___________________________________________________________
51
Chapter 3. Structures and Arrays. ____________________________________
3.2 Arrays
Note also that, the array elements can be defined by either the
standard data type (int, char or float) or any other data-type
including structures, arrays and classes.
___________________________________________________________
54
Chapter 3. Structures and Arrays. ____________________________________
the array has 5 elements and in the list of initial values within
braces { } we have specified 5 values, one for each element.
Array_name[element_index]
myarray[2] = 75;
X = myarray[2];
myarray[0] = a;
b = myarray [a+2];
myarray[myarray[a]] = myarray[2] + 5;
If you read carefully, you will see that a type specifier precedes a
variable or array declaration, while it never precedes an access.
// arrays example
#include <iostream>
using namespace std;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{
result += myarray[n];
}
cout << result;
return 0;
}
12206
___________________________________________________________
57
Chapter 3. Structures and Arrays. ____________________________________
myarray[1][3]
___________________________________________________________
58
Chapter 3. Structures and Arrays. ____________________________________
___________________________________________________________
59
Chapter 3. Structures and Arrays. ____________________________________
None of the two source codes above produce any output on the
screen, but both assign values to the memory block called
myarray in the following way:
#define HEIGHT 3
to:
#define HEIGHT 4
___________________________________________________________
60
Chapter 3. Structures and Arrays. ____________________________________
Fun1 (myarray);
___________________________________________________________
61
Chapter 3. Structures and Arrays. ____________________________________
// arrays as parameters
#include <iostream>
using namespace std;
int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;
}
5 10 15
2 4 6 8 10
As you can see, the first parameter (int arg[]) accepts any array
whose elements are of type int, whatever its length. For that
reason, a second parameter is included to tell the function the
length of each array that we pass to it as its first parameter. This
allows the for loop that prints out the array to know the range to
iterate in the passed array without going out of range.
data_type array_name[][depth][depth]
___________________________________________________________
62
Chapter 3. Structures and Arrays. ____________________________________
Notice that the first brackets [] are left blank while the following
ones are not. This is because the compiler must be able to
determine the depth of each additional dimension within function.
// array of structures
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#define N_MOVIES 3
struct movies_t
{
string title;
___________________________________________________________
63
Chapter 3. Structures and Arrays. ____________________________________
int year;
} films [N_MOVIES];
int main ()
{
string mystr;
int n;
___________________________________________________________
65
Chapter 3. Structures and Arrays. ____________________________________
Notice how a null character ('\0') has been included after the valid
content in order to indicate the end of the sequence. The panels
in gray color represent char elements with undetermined values.
___________________________________________________________
66
Chapter 3. Structures and Arrays. ____________________________________
end of the sequence and that, in the second case, when using
double quotes (") it is appended automatically.
mytext = "Hello";
mytext[] = "Hello";
The reason for this may become more comprehensible once you
know a bit more about pointers, since then it will be clarified that
an array is in fact a constant pointer pointing to a block of
memory.
___________________________________________________________
68
Chapter 3. Structures and Arrays. ____________________________________
#include <iostream>
using namespace std;
int main ()
{
char question[] = "Please, enter your first name: ";
char greeting[] = "Hello, ";
char yourname [80];
cout << question;
cin >> yourname;
cout << greeting << yourname << "!";
return 0;
}
Please, enter your first name: John
Hello, John!
___________________________________________________________
69
Chapter 3. Structures and Arrays. ____________________________________
mystring;
char mycharseq[]="some text";
mystring = mycharseq;
3.3 Summary
___________________________________________________________
70
Chapter 4
4.1 Introduction
pattern. For example, if we are looking for cell 1776 we know that
it is going to be right between cells 1775 and 1777, exactly one
thousand cells after 776 and one thousand cells before cell 2776.
Pointers are a very powerful feature of the C++ language that has
many uses in advanced programming. Pointers are what they
sound like...pointers; they point to locations/places in memory.
Perhaps, an analogy would be illuminating: a pointer is like a sign
pointing to a window. It is not the window itself but an indication
to where the window is. Similarly, a pointer is like a postal address
which tells us where it is, but is not the actual building of the post.
___________________________________________________________
72
Chapter 4. Pointers and Dynamic Memory. ____________________________
Pointers can be confusing, and at times, you may wonder why you
would ever want to use them. The truth is that they can make
some things in programming much easier. For example, pointers
are often used with arrays, structure and objects to move
information between functions. This is because, these objects tend
to be large, and thus making it is difficult to pass the whole array
or structure between functions (as we would normally do with
variables). The solution proposed is that; pass only the memory
address of the array or the structure. It is also possible to use
pointers to dynamically allocate memory locations. Indeed,
pointers allow setting up certain programming techniques such as
stacks, linked lists and queues. Farther ahead, we will see how
this type of variable is used and declared.
data_type *pointer_name;
___________________________________________________________
73
Chapter 4. Pointers and Dynamic Memory. ____________________________
Where, data_type is the type of the data value that the pointer is
intended to point to. This type is not the type of pointer itself but
the type of the data the pointer points to. The asterisk symbol * is
the key of declaring a pointer. If you use it before a variable
name, it will declare the variable as a pointer. In other words,
pointer variables are declared using a "*" and has data types like
the other variables we have seen previously. For example:
int* number;
char* character;
float* greatnumber;
Note that, the pointer data type may be a standard data type like
int and char or a user defined data type like structures and arrays.
In the following, we will first deal with pointers to basic data types
and then we deal with pointers to both structures and arrays.
___________________________________________________________
74
Chapter 4. Pointers and Dynamic Memory. ____________________________
ptr = &num ;
This would assign the address of variable num to ptr. This means
that, when preceding the name of a variable with the reference
operator (&) we are no longer talking about the content of the
variable itself but about its reference (i.e., its address in memory).
num = 25;
fred = num;
ptr = #
___________________________________________________________
76
Chapter 4. Pointers and Dynamic Memory. ____________________________
Finally, the third statement copies to ptr not the value contained
in num but a reference to it (i.e., its address which is 1776). The
reason is that, in this third assignation operation, we have
preceded the identifier num with the reference operator (&), so
we were no longer referring to the value of num but to its
reference (its address in memory). The variable that stores the
reference to another variable (like ptr in the previous example) is
what we call a pointer.
var1 = *ptr;
You must clearly differentiate that the ptr refers to the value
1776, while *ptr (with asterisk * preceding the identifier) refers
to the value stored at address 1776, which in this case is 25.
// my first pointer
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer; // * declaring a pointer
mypointer = &firstvalue;
*mypointer = 10; // * deference operator
mypointer = &secondvalue;
*mypointer = 20; // * deference operator
firstvalue is 10
secondvalue is 20
___________________________________________________________
79
Chapter 4. Pointers and Dynamic Memory. ____________________________
// more pointers
#include <iostream>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; //value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
firstvalue is 10
secondvalue is 20
___________________________________________________________
80
Chapter 4. Pointers and Dynamic Memory. ____________________________
This declares the two pointers used in the previous example. But
notice that there is an asterisk (*) for each pointer, in order for
both to have type int* (pointer to int). If we had written:
p1 would indeed have int* type, but p2 would have type int.
Spaces do not matter at all for this purpose. Anyway, simply
remember to put one asterisk per pointer.
___________________________________________________________
81
Chapter 4. Pointers and Dynamic Memory. ____________________________
#include <iostream.h>
int main()
{
int * ptr_a, ptr_b;
int num_c = 4, num_d = 7;
___________________________________________________________
82
Chapter 4. Pointers and Dynamic Memory. ____________________________
ptr_a = &num_c;
___________________________________________________________
83
Chapter 4. Pointers and Dynamic Memory. ____________________________
int number;
int *ptr = &number;
int number;
int *ptr;
ptr = &number;
int number;
int *ptr;
*ptr = &number;
that is incorrect, and anyway would not have much sense in this
case if you think about it.
___________________________________________________________
84
Chapter 4. Pointers and Dynamic Memory. ____________________________
As in the case of arrays, the compiler allows the special case that
we want to initialize the content at which the pointer points with
constants at the same moment the pointer is declared:
___________________________________________________________
85
Chapter 4. Pointers and Dynamic Memory. ____________________________
ptr[4] = '!';
*(ptr+4) = '!';
// increaser
#include <iostream>
using namespace std;
int main ()
{
char a = 'x';
int b = 1602;
increase (&a);
increase (&b);
cout << a << ", " << b;
return 0;
}
y, 1603
___________________________________________________________
87
Chapter 4. Pointers and Dynamic Memory. ____________________________
int * p;
p = 0; // p has a null pointer value
___________________________________________________________
88
Chapter 4. Pointers and Dynamic Memory. ____________________________
char *mychar;
short *myshort;
long *mylong;
and that we know that they point to memory locations 1000, 2000
and 3000 respectively.
So if we write:
mychar++;
myshort++;
mylong++;
___________________________________________________________
89
Chapter 4. Pointers and Dynamic Memory. ____________________________
mychar = mychar + 1;
myshort = myshort + 1;
mylong = mylong + 1;
Both the increase (++) and decrease (--) operators have greater
operator precedence than the dereference operator (*), but both
have a special behavior when used as suffix (the expression is
evaluated with the value it had before being increased).
Therefore, the following expression may lead to confusion:
*p++
___________________________________________________________
90
Chapter 4. Pointers and Dynamic Memory. ____________________________
(*p)++
If we write:
*p++ = *q++;
*p = *q;
++p;
++q;
___________________________________________________________
91
Chapter 4. Pointers and Dynamic Memory. ____________________________
struct point
{
float x;
float y;
};
point point_a;
point * ptr;
ptr = &point_a;
___________________________________________________________
92
Chapter 4. Pointers and Dynamic Memory. ____________________________
// pointer to structure
#include <iostream.h>
struct product
{
char name[4];
double price;
double mark;
};
int main()
{
product item, *Ptr;
item.name = "ABC"; //Initializing parts of Item
item.price = 5.43;
item.mark = 1000;
ptr = &item;
___________________________________________________________
93
Chapter 4. Pointers and Dynamic Memory. ____________________________
ptr = num;
Both ptr and num would be equivalent and would have the same
properties with respect to the array, where they are points to the
___________________________________________________________
94
Chapter 4. Pointers and Dynamic Memory. ____________________________
first array element. Thus, num[0], *num, and *ptr are all now
different variable names denoting the first element. Thus, the
following two expressions are equivalent and valid either if num is
a pointer or if num is an array.
Now also there are alternative names to the other array elements.
We can refer to them either as
___________________________________________________________
95
Chapter 4. Pointers and Dynamic Memory. ____________________________
num = p;
// more pointers
#include <iostream>
using namespace std;
int main ()
{
int num[5];
int * p;
p = num;
*p = 10;
p++;
*p = 20;
p = &num[2];
*p = 30;
p = num + 3;
*p = 40;
p = num;
*(p+4) = 50;
for (int i=0; i<5; i++)
cout << num[i] << ", ";
return 0;
}
___________________________________________________________
96
Chapter 4. Pointers and Dynamic Memory. ____________________________
#include <iostream.h>
___________________________________________________________
97
Chapter 4. Pointers and Dynamic Memory. ____________________________
int main()
{
const int Dim = 10;
int i, List[Dim];
#include <iostream.h>
struct Complex
{
double Real;
double Imaginary;
};
int main()
{
Complex I;
I.Real=0;
I.Imaginary=1;
___________________________________________________________
99
Chapter 4. Pointers and Dynamic Memory. ____________________________
if (I.Imaginary>=0)
cout << I.Real << "+" << I.Imaginary
<< "i" << endl;
else
cout << I.Real << "-" << I.Imaginary
<< "i" << endl;
Conjugate(&I);
if (I.Imaginary>=0)
cout << I.Real << "+" << I.Imaginary
<< "i" << endl;
else
cout << I.Real << "-" << I.Imaginary
<< "i" << endl;
return 1;
}
___________________________________________________________
100
Chapter 4. Pointers and Dynamic Memory. ____________________________
___________________________________________________________
101
Chapter 4. Pointers and Dynamic Memory. ____________________________
int * newptr;
newptr = new int [5];
___________________________________________________________
103
Chapter 4. Pointers and Dynamic Memory. ____________________________
int * newptr;
newptr = new (nothrow) int [5];
if (newptr == 0)
{
// error assigning memory. Take measures.
};
___________________________________________________________
104
Chapter 4. Pointers and Dynamic Memory. ____________________________
delete pointer;
delete [] pointer;
#include <iostream.h>
typedef int *IntPtrType;
int main()
{
IntPtrType ptr_a, ptr_b; /* LINE 7 */
ptr_a = new int; /* LINE 9 */
*ptr_a = 4;
ptr_b = ptr_a; /* LINE 11 */
cout << *ptr_a << " " << *ptr_b << "\n";
ptr_b = new int; /* LINE 15 */
*ptr_b = 7; /* LINE 16 */
cout << *ptr_a << " " << *ptr_b << "\n";
___________________________________________________________
105
Chapter 4. Pointers and Dynamic Memory. ____________________________
delete ptr_a;
ptr_a = ptr_b; /* LINE 21 */
cout << *ptr_a << " " << *ptr_b << "\n";
delete ptr_a; /* LINE 25 */
return 0;
}
4 4
4 7
7 7
___________________________________________________________
106
Chapter 4. Pointers and Dynamic Memory. ____________________________
Finally, after the "delete" statement in lines 25, the program state
returns to:
In the first and last diagrams above, the pointers "ptr_a" and
"ptr_b" are said to be dangling. Note that "ptr_b" is dangling at
the end of the program even though it has not been explicitly
included in a "delete" statement.
#include <iostream>
...
delete ptr_a;
ptr_a = NULL;
___________________________________________________________
107
Chapter 4. Pointers and Dynamic Memory. ____________________________
ptr_b = NULL;
...
if (ptr_a != NULL)
{
*ptr_a = ...
...
}
int num_ptr;
num_ptr = new int [10];
delete [] num_ptr;
// dynamic memory
#include <iostream>
using namespace std;
___________________________________________________________
108
Chapter 4. Pointers and Dynamic Memory. ____________________________
int main ()
{
int i;
int * p;
cout << "How many numbers would you like to type? ";
cin >> i;
p= new (nothrow) int[i];
if (p == 0)
cout << "Error: memory could not be allocated";
else
{
for (int n=0; n<i; n++)
{
cout << "Enter number: ";
cin >> p[n];
}
cout << "You have entered: ";
for (n=0; n<i; n++)
cout << p[n] << ", ";
delete[] p;
}
return 0;
}
How many numbers would you like to type? 5
Enter number : 75
Enter number : 436
Enter number : 1067
Enter number : 8
Enter number : 32
You have entered: 75, 436, 1067, 8, 32,
Notice how the value within brackets in the new statement is not
a constant value but is a variable value i entered by the user. But
the user could have entered a value for i so big that our system
could not handle it. For example, when tried to give a value of 1
billion to the question "How many numbers", my system could not
allocate that much memory for the program and you will get the
text message that prepared for this case (Error: memory could not
___________________________________________________________
109
Chapter 4. Pointers and Dynamic Memory. ____________________________
4.9 Summary
___________________________________________________________
110
Chapter 5. Linked Lists. ___________________________________________________
Chapter 5
Linked Lists
___________________________________________________________
112
Chapter 5. Linked Lists. ___________________________________________________
This linked list has three nodes in it, each with a link to the
next node in the series. Each of the big blocks is a struct that
has a pointer to another one. Remember that the pointer
only stores the memory location of something; it is not that
thing, so the arrow goes to the next one. At the end, there is
nothing for the pointer to point to, so it does not point to
anything, it should be set to "NULL" to prevent it from
accidentally pointing to a totally arbitrary and random
location in memory (which is very bad). There is also another
special pointer, here called pointer, which points to the first
link in the chain so that we can keep track of it.
struct node
{
char name[20]; // Name of up to 20 letters
int age; // The current age in years
float height; // In metres
node *next; // Pointer to next node
};
___________________________________________________________
113
Chapter 5. Linked Lists. ___________________________________________________
We can refer to the new node as *temp, i.e. "the node that
temp points to". When the fields of this structure are referred
to, brackets can be put round the *temp part, as otherwise
the compiler will think we are trying to refer to the fields of
the pointer. Alternatively, we can use the new pointer
notation. That's what I shall do here.
The last line sets the pointer from this node to the next to
NULL, indicating that this node, when it is inserted in the
list, will be the last node. Having set up the information, we
have to decide what to do with the pointers.
___________________________________________________________
115
Chapter 5. Linked Lists. ___________________________________________________
Adding at Start:
if (start_ptr == NULL)
start_ptr = temp;
Adding at end:
___________________________________________________________
116
Chapter 5. Linked Lists. ___________________________________________________
The loop will terminate when temp2 points to the last node
in the chain, and this happens when the pointer next in that
node to NULL. When it has found it, it sets the pointer from
that last node (temp2->next) to point to the node we have
just declared. The link joining the last two nodes can be
defined as:
temp2->next = temp;
The full code for adding a node at the end of the list is
shown below, in its own little function:
void add_node_at_end ()
{
node *temp, *temp2; // Temporary pointers
if (start_ptr == NULL)
start_ptr = temp;
else // this is not NULL - list not empty!
{
temp2 = start_ptr;
while (temp2->nxt != NULL)
{
temp2 = temp2->next; // Move to next node
}
temp2->next = temp;
}
}
temp = start_ptr;
do
{
if (temp == NULL)
cout << "End of list" << endl;
else
{
// Display details for what temp points to
cout << "Name: " << temp->name << endl;
cout << "Age: " << temp->age << endl;
cout << "Height: " << temp->height;
cout << endl<< endl; // Blank line
___________________________________________________________
119
Chapter 5. Linked Lists. ___________________________________________________
For simplicity, I shall just deal with deleting one from the
start or from the end. When a node is deleted, the space that
it took up should be reclaimed. Otherwise the computer will
eventually run out of memory space. This is done with the
delete instruction:
Now that the first node has been safely tagged (so that we
can refer to it even when the start pointer has been
reassigned), we can move the start pointer to the next node
in the chain:
void delete_start_node()
{
node *temp;
temp = start_ptr;
start_ptr = start_ptr->next;
delete temp;
}
void delete_end_node()
{
node *temp1, *temp2;
if (start_ptr == NULL)
cout << "The list is empty!" << endl;
else
{
temp1 = start_ptr;
while (temp1->next != NULL)
{
temp2 = temp1;
temp1 = temp1->nxt;
}
delete temp1;
temp2->nxt = NULL;
}
}
void delete_end_node()
{
node *temp1, *temp2;
if (start_ptr == NULL)
cout << "The list is empty!" << endl;
else
{
temp1 = start_ptr;
if (temp1->next == NULL) // This part is new!
{
delete temp1;
start_ptr = NULL;
}
else
{
while (temp1->next != NULL)
{
temp2 = temp1;
temp1 = temp1->next;
}
delete temp1;
temp2->next = NULL;
}
}
}
___________________________________________________________
124
Chapter 5. Linked Lists. ___________________________________________________
node *current;
current = start_ptr;
Moving Forwards:
It's easy to get the current pointer to point to the next node
in the list (i.e. move from left to right along the list). If you
want to move current along one node, use the next field of
the node that it is pointing to at the moment:
current = current->next;
___________________________________________________________
125
Chapter 5. Linked Lists. ___________________________________________________
if (current->next == NULL)
cout << "You are at the end of list." << endl;
else
current = current->next;
Moving Backwards:
We can tell when this happens, as the nxt pointer from that
node will point to exactly the same place in memory as the
current pointer (i.e. the current node).
if (current == start_ptr)
cout << "You are at the start of list" << endl;
else
{
node *previous; // Declare the pointer
previous = start_ptr;
current = previous;
}
Now that you have the facility to move back and forth, you
need to do something with it. Firstly, let's see if we can alter
the details for that particular node in the list:
cout << "Please enter the new name of the person: ";
cin >> current->name;
cout << "Please enter the new age of the person : ";
cin >> current->age;
cout << "Please enter the new height of the person : ";
cin >> current->height;
___________________________________________________________
127
Chapter 5. Linked Lists. ___________________________________________________
Deleting a node:
___________________________________________________________
128
Chapter 5. Linked Lists. ___________________________________________________
Here is the code for deleting the node after the current one.
It includes a test at the start to test whether the current
node is the last one in the list:
if (current->next == NULL)
cout << "There is no node after current" << endl;
else
{
node *temp;
temp = current->next;
current->next = temp->next; // Could be NULL
delete temp;
}
Inserting a node:
if (current->next == NULL)
add_node_at_end();
else
{
node *temp;
new temp;
get_details(temp);
// Make the new node point to the same
// thing as the current node
temp->next = current->next;
// Make the current node point to the new node
current->next = temp;
}
___________________________________________________________
129
Chapter 5. Linked Lists. ___________________________________________________
___________________________________________________________
130
Chapter 6: Stacks and Queues. _________________________________________
Chapter 6
131
Chapter 6: Stacks and Queues. _________________________________________
6.1.1 Definition
132
Chapter 6: Stacks and Queues. _________________________________________
F
E
D
C
B
A
133
Chapter 6: Stacks and Queues. _________________________________________
J
I I I
H H H H H
top G G G G G G G
F F F F F F F F F K
134
E E E E E E E E E E E E
D D D D D D D D D D D D D G
C C C C C C C C C C C C C C C
B B B B B B B B B B B B B B B
A A A A A A A A A A A A A A A
(a) (b) (c) (d) (e) (f) (g) (h) (i) (j) (k) (l) (m) (n) (o)
Figur 2.2 Motion picture of a stack
Chapter 6: Stacks and Queues. _________________________________________
135
Chapter 6: Stacks and Queues. _________________________________________
136
Chapter 6: Stacks and Queues. _________________________________________
137
Chapter 6: Stacks and Queues. _________________________________________
i = stacktop(s);
is equivalent to
138
Chapter 6: Stacks and Queues. _________________________________________
i = pop(s);
139
Chapter 6: Stacks and Queues. _________________________________________
140
Chapter 6: Stacks and Queues. _________________________________________
struct stack s;
141
Chapter 6: Stacks and Queues. _________________________________________
struct stackelement
{
int etype; /* etype equals INT, FLOAT,or STRING */
/* depending on the type of the */
/* corresponding element. */
union
{
int ival;
142
Chapter 6: Stacks and Queues. _________________________________________
float fval;
char *pval; /* pointer to a string */
} element;
};
struct stack
{
int top;
struct stackelement items[STACKSIZE];
};
struct stack s;
143
Chapter 6: Stacks and Queues. _________________________________________
if (s.top == -1)
/* stack is empty */
else
/* stack is not empty */
144
Chapter 6: Stacks and Queues. _________________________________________
return(TRUE);
else
return(FALSE);
} /* end empty */
if (empty (&s))
/* stack is empty */
else
/* stack is not empty */
empty(s)
145
Chapter 6: Stacks and Queues. _________________________________________
146
Chapter 6: Stacks and Queues. _________________________________________
147
Chapter 6: Stacks and Queues. _________________________________________
if (ps->top == -1)
return(TRUE);
else
return(FALSE);
148
Chapter 6: Stacks and Queues. _________________________________________
149
Chapter 6: Stacks and Queues. _________________________________________
150
Chapter 6: Stacks and Queues. _________________________________________
x = pop (&s);
151
Chapter 6: Stacks and Queues. _________________________________________
152
Chapter 6: Stacks and Queues. _________________________________________
Assume that the array s.items is full and that the C push
routine is called. Remember that the first array position is
0 and the arbitrary size (STACKSIZE) chosen for the array
s.items is 100. The full array is then indicated by the
condition s.top == 99, so that position 99 (the 100th
element of the array) is the current top of the stack. When
push is called, s.top is increased to 100 and an attempt is
made to insert x into x.items[100].
153
Chapter 6: Stacks and Queues. _________________________________________
return;
} /* end push */
x = pop(s);
154
Chapter 6: Stacks and Queues. _________________________________________
155
Chapter 6: Stacks and Queues. _________________________________________
6.2.1 Definition
156
Chapter 6: Stacks and Queues. _________________________________________
Front
A B C
Rear
(a)
Front
B C
Rear
(B)
Front
B C D E
Rear
(c)
157
Chapter 6: Stacks and Queues. _________________________________________
insert(q, A);
insert(q, B);
insert(q, D);
158
Chapter 6: Stacks and Queues. _________________________________________
q.items [++q.rear] = x;
x = q.items [q.front++];
159
Chapter 6: Stacks and Queues. _________________________________________
q.items q.items
4 4
3 3
2 2 C q.rear = 2
1 1 B
q.front = 0
0 0 A q.front = 0
q.rear = -1
(a) (b)
q.items q.items
4 4 E q.rear = 4
3 3 D
2 C q.front = q.rear = 2 2 C q.front = 2
1 1
0 0
(c) (d)
Figure 6.5
160
Chapter 6: Stacks and Queues. _________________________________________
Raised Problem:
Solution:
x = q.items[0];
q.items[i] = q.iterms[i+1];
q.rear--;
162
Chapter 6: Stacks and Queues. _________________________________________
q.items q.items
4 E q.rear = 4 4 E
3 D 3 D
2 C q.front = 2 2 C q.front = 2
1 1
0 0 F q.rear = 0
(a) (b)
q.items q.items
4 E q.front = 4 4 E q.front = 4
3 3
2 2
1 1 G q.rear = 1
0 F q.rear = 0 0 F
(c) (d)
q.items
4
3
2
1 G q.rear = 1
0 F q.front = 0
(e)
Figure 6.6
163
Chapter 6: Stacks and Queues. _________________________________________
164
Chapter 6: Stacks and Queues. _________________________________________
Note that q.front and q.rear are initialized to the last index
of the array, rather than to -1 or 0, because the last
element of the array immediately precedes the first one
within the queue under this representation. Since q.rear
equals q.front, the queue is initially empty.
Empty Operation:
165
Chapter 6: Stacks and Queues. _________________________________________
if (empty(&q))
/* queue is empty */
else
/* queue is not empty */
Remove Operation:
if (pq->front == MAXQUEUE-1)
pq->front = 0;
else
(pq->front)++;
return (pq->items[pq->front]);
} /* end remove */
166
Chapter 6: Stacks and Queues. _________________________________________
Insert Operation
167
Chapter 6: Stacks and Queues. _________________________________________
q.items q.items
4 E q.rear = 4 4 E
3 D 3 D
2 C 2 C
1 q.front = 1 1 q.front = 1
0 0 F q.rear = 0
(a) (b)
q.items
4 E
3 D
2 C
1 G q.front = q.rear = 1
0 F
(c)
Figure 6.7
168
Chapter 6: Stacks and Queues. _________________________________________
pq->items[pq->rear] = x;
return;
} /* end insert */
169
Chapter 6: Stacks and Queues. _________________________________________
170
References. __________________________________________________________
REFERENCES
1- D. S. Malik, and Dr. D. S. Malik, “Data Structures
Using C++”, Course Technology, 2003.
171