3. Course contents
Array Data Structure (Declaration, Initialization, Updation)
Why we need Arrays?
Pros & Cons
Character String as Array
Pointers: Increment & Decrement
Multi-Dimensional Array
Exercises using Arrays
Home work using Arrays
4. Array
An array is a homogeneous data structure that can contain multiple elements.
In most programming languages array elements are stored in contiguous
memory space. This data structure is homogeneous since all elements stored
are of same type.
0 1 2 3 4 5 6 7 8 9
array
Starting index Last index
Remember: number of
elements are 10
5. Array
Array name is reference to memory location where first elment of array is stored
Array elmements can be accessed using array name and a non-negative integer index e.g.
say records is an array then records[2] refers to 3rd elment of array
Index values for an N element array range from 0 to N-1
Array elements can be accessed randomly (no sequence is required to follow for it)
0 1 2 3 4 5 6 7 8 9
6. Array Declaration
Syntax : datatype anArrayname[sizeofArray];
int data[10];
As the result of above statement execution an integer array of ten elements is
created within the memory of computer
First valid index is 0 and last valid index is 9
Array elements can be refered as data[0], data[1], data[2], … , data[9]
0 1 2 3 4 5 6 7 8 9
7. Array initialization
Syntax : datatype anArrayname[sizeofArray]= {comma separated
values};
int data[10]={5, 3, 12, 23, 8, 37, 6, 10, 55, 4};
As the result of above statement execution an integer array of ten elements is
created within the memory of computer and are initialized with provided values
0 index value is initialized with 5, 1 index value is initialized with 3, 2 index value
is initialized with 12 so on and so forth
5 3 12 23 8 37 6 10 55 4
0 1 2 3 4 5 6 7 8 9
Elements
Indexes
8. Array initialization
int data[5];
data[0]=6; data[1]=12; data[2]=18; data[3]=24; data[4]=30;
As the result of first statement execution an integer array of ten elements is created
within the memory of computer. Statements in second line are initializing array
elements:
6
12
18
24
30
0
1
2
3
4
index
Array values
9. Array … first program
#include <iostream>
int main(int argc, char** argv) {
int values[10]={5, 10, 3, 18, 7, 12, 34, 26, 0, 47};
for(int i=0; i<10; i++)
std::cout<<values[i]<<std::endl;
return 0;
}
A simple program that initializes a ten element integer
array and prints all elements using for loop
10. Array … Updating elements
array[index] = new-value;
A declared array element can be assigned a valid value during within the scope of
array. See below:
#include <iostream>
int main(int argc, char** argv) {
int values[10]={1,2,3,4,5,6,7,8,9,10};
values[2]=20; values[4]=30; values[9]=11;
return 0;
}
11. Array … search an element
Write down a small program
using an array containing ten
integer values (properly
initialized). Input an integer
value from user and search
whether given value exists in
array or not.
Program:
12. Array … Why we need it?
It is often required during programming that some operation is required to be
applied over set of fixed size data items e.g. search a specific item from a set of
values, sum the values of list of numbers, initialize all quantities within a list with
some given value etc
To meet the situations above and many more, almost all programming languages
support arrays or similar data structures
Wherever we want to use multiple variables of same type of data, array can be very
handy
Array allows to declare and initialize multiple variables of same type using single
statement
Instead of apply some operation on individual items of same type, we can use a
loop to do the same on an array (very convenient)
13. Array … pros and cons
Advantages Disadvantages
It is used to represent multiple data items of same
type by using only single name
Insertion / deletion of elements is not straight
forward and requires a lot of effort
It can be used to implement other data structures
like linked lists, stacks, queues, trees, graphs etc.
Most programming languages offer static arrays
not allowing elements beyond defined boundaries
Common mathematical models e.g. matrices,
tables can be represented by 2D arrays
Larger arrays may cause loss of memory i.e. whole
memory is allocated even when few elements are
availablel
Elements can be accessed randomly Multi-dimension arrays are neither easier to
implement nor to maintain
Suitable data structure when elements are already
known
Few languages (C / C++) does not provide array
boundary check introducing inappropriate access
to application data
One can use same name for a collection of similar
elements
We must know in advance that how many
elements are to be stored in array
14. character string as array
In C/C++ strings are treated like as an array of characters e.g.
char message[]=“welcome”;
Above character is stored in memory like:
w e l c o m e 0
Every string is terminated by a null character ‘0’
15. character string as array …
If we initialize a character array with a size e.g.
char message[12] = “welcome”;
Then memory actually looks like:
Last four characters spaces are unused.
w e l c o m e 0
16. character string as array …
We can actually access individual elements of a character array:
char message[]=“welcome”;
std:cout<<message[3]<<std:endl;
Output:
c
17. character string as array …
Creating a string as character array requires at compile time how many character
will be stored in it. Such arrays are called static arrays. Examples below:
char message[]=“message”; // eight characters will be allocated for this array
char country[20]=“Pakistan”; // nine chracters will be allocated for this array
18. Array name AND pointer
Array name is a pointer and it points to initial position of memory allocated to store
array contents. It can be assigned to a character pointer type of variable and that in
return can access array contents like original array name. Example below:
char message[]="welcome";
char *pointer=message;
std::cout<<pointer[3]<<std::endl;
19. Multi-dimensional arrays
C/C++ allows multi-dimensional arrays. Following is the syntax for declaring them:
datatype array_name[dim1][dim2]….[dimN];
A typical two dimensional integer array can be declared as:
int arr[5][4];
This 2D array can be imagined as a table and can be visualized as:
arr[0][0] arr[0][1] arr[0][2] arr[0][3]
arr[1][0] arr[1][1] arr[1][2] arr[1][3]
arr[2][0] arr[2][1] arr[2][2] arr[2][3]
arr[3][0] arr[3][1] arr[3][2] arr[3][3]
arr[4][0] arr[4][1] arr[4][2] arr[4][3]
Row 0
Row 1
Row 2
Row 3
Row 4
Col 0 Col 3
Col 2
Col 1
21. Exercise questions
Q#01. Write down a function with following prototype:
int find(data, target)
where data is an integer array and target is an integer value. Find() searches through data
and returns the index of value that is equal to target. It returns -1 if no elment in data is
equal to target.
Q#02. Write down a function with following prototype:
int find(data, target)
where data is an integer array and target is an integer value. Find() searches through data
and returns the index of last occurance of value that is equal to target. It returns -1 if no
elment in data is equal to target.
22. Exercise questions
Q#03. Write down a function with following prototype:
int count(data, target)
where data is an integer array and target is an integer value. Count() searches through data
and number of occurances of target value within the data. It returns 0 if no elment in data is
equal to target.
Q#04. Write down a function with following prototype:
void double(data)
where data is an integer array. Double() updates all values within the data with double of its
original values.
23. Homework for next class
Q#01. Write a function equal(data1, data2) as below:
int equal(data1, data2) where both data1 and data2 are integer arrays. Equal()
returns 1 if both arrays have same values and same order. It returns 0 otherwise.
Example:
If data1={1,2,3} and data2={1,2,3}, equal() returns 1
If data1={1,2,3} and data2={2, 1,3}, equal() returns 0
If data1={1,2,3} and data2={4,2,3}, equal() returns 0
If data1={1,2,3} and data2={1,2,3,4}, equal() returns 0
If data1={1,2,3} and data2={4,5,6}, equal() returns 0
24. Homework for next class
Q#01. Write a function equal(data1, data2) as below:
int equal(data1, data2) where both data1 and data2 are integer arrays. Equal()
returns 1 if both arrays have same values. It returns 0 otherwise.
Example:
If data1={1,2,3} and data2={1,2,3}, equal() returns 1
If data1={1,2,3} and data2={2, 1,3}, equal() returns 1
If data1={1,2,3} and data2={4,2,3}, equal() returns 0
If data1={1,2,3} and data2={1,2,3,4}, equal() returns 0
If data1={1,2,3} and data2={4,5,6}, equal() returns 0
27. Course contents
Linked List
Linked List ADT
Linked List Representation
Linked List Operations (Idea & Implementation)
PrintAll
AddNode
AppendNode
InsertNode
DeleteNode
Size
28. Linked Lists
A finite and ordered sequence of items
connected together through links is
called a linked list or simply a list.
Items in a linked list are generally called nodes
A node in a linked list consists of two parts i. Data
part ii. Link part
Data part is for storage of value(s) and link part
contains the address of simply another node of
same list
First node is commonly known as start node
29. Linked Lists …
A list object contains the reference to start node only
First node is directly accessed by linked-list object and other nodes are
accessed one by one using the links to other elements
Since list nodes can only be accessed one by one sequentially, list data
structure is also categorized as a linear data structure
Linked List
30. Linked Lists …
List elements are ordered only in a sense that they can be accessed one by
one beginning from start node (ordered does not mean sorted)
A list is said to be empty if its start node points to NULL
NULL is a special pointer that indicates the end of list
First node of list (start node) is called the head and last node is called the tail
List can grow and shrink dynamically (generally no limit on number of
elements)
When list grows, memory allocated for it also grows i.e. memory allocated for
list directly refers to number of nodes in the list
31. ADT
An abstract data type (ADT) is a mathematical model for data types
where a data type is defined by its behavior (semantics) from the point
of view of a user of the data, specifically in terms of possible values,
possible operations on data of this type, and the behavior of these
operations.
https://en.wikipedia.org/wiki/Abstract_data_type
33. Linked list ADT … Node operations
Operation Description
Node(int) Construtor that initializes node ‘data’ members with
given value & node pointer ‘next’ to NULL
void Set_data(int) Sets the data member ‘data’ with provided value
int get_data() Returns current value of ‘data’
void set_next(Node*) Sets the data member ‘next’ with provided ‘pointer’
Node* get_next() Returns the current value of ‘next’ pointer
34. Linked list ADT … linklist operations
Operation Description Pseudo Code
LinkList() A constructor that
initializes data member
‘start’ to NULL
Assign NULL to ‘start’
size() A method that returns
the size of Linked List
i.e. number of elements
in it
Take a temprorary node pointer ‘temp’
and point it to ‘start’ node pointer
Set ‘count’ to zero
It traverses all nodes one by one by
pointing ‘temp’ pointer to ‘next’ pointer
and increasing the ‘count’ by one in
every iteration
Iterations stop when ‘temp’ points to
NULL address
At this point value of ‘count’ is returned
35. Linked list ADT … linklist operations
Operation Description Pseudo Code
print_all() Prints the ‘data’ values
for all nodes in Linked
List
Take a temprorary node pointer ‘temp’
and point it to ‘start’ node pointer
It traverses all nodes one by one by
printing value of ‘data’ for node ‘temp’ is
pointing to and then pointing ‘temp’ to
‘next’ pointer
Iterations stop when ‘temp’ points to
NULL value
37. Linked list operations … add node
Operation Description Pseudo Code
add_node(key) Adds a new node
to start of list
Creates a new node ‘temp’ with provided
‘key’ as ‘data’ value
Points ‘next’ pointer to ‘start’
Moves ‘start’ to ‘temp’
38. Linked list operations … append node
Operation Description Pseudo Code
append_node(key) Adds a new
node to end of
list
Create a new node ‘n’ using given ‘key’ as
its ‘data’ and NULL as ‘next’ pointer
Creates a node pointer ‘temp’ and point it
to start
If ‘temp’ points to NULL, assign ‘n’ to ‘start’
Otherwise, traverse ‘temp’ to the last
nodes of list using ‘next’ pointers of
intermediate nodes
Assign ‘n’ to ‘next’ of ‘temp’
40. Linked List operations … search node
Operation Description Pseudo Code
Search_node(key) Searches node
from list whose
‘data’ value is
equal to ‘key’
provided and
returns its
reference
Take a node pointer ‘temp’ and point it to
‘start’
Iterate ‘temp’ through list nodes until
either a node with ‘data’ equal to ‘key’ is
found or list ends (‘temp’ points to NULL)
Return the node pointer ‘temp’ is pointing
to
41. Linked List operations … search node
No node in Linked List had same value of ‘data’ as of ‘key’ provided to procedure
‘NULL’ value is return as response
42. Linked List operations … search node
Node in Linked List having ‘data 4’ as its value same as of ‘key’
Pointer to ‘data 4’ is returned as response
43. Linked List operations … insert node
Operation Description Pseudo Code
insert_node(after,
key)
Inserts a new
node into
Linked List
after a node
with given
value
Call the search(after) procedure as
described earlier
If Node pointer returned as above call is
equl to NULL, insertion not possible
Otherwise (a valid node pointer is
returned say ‘temp’), create a new node ‘n’
Set ‘key’ to the ‘data’ of ‘n’ and set ‘next’ of
‘temp’ to ‘next’ of ‘n’
45. Linked List operations … append node
Operation Description Pseudo Code
Append_node(key) Adds a new
node to end of
list
Create a new node ‘n’ using given ‘key’ as
its ‘data’ and NULL as ‘next’ pointer
Creates a node pointer ‘temp’ and point it
to start
If ‘temp’ points to NULL, assign ‘n’ to ‘start’
Otherwise, traverse ‘temp’ to last nodes
using ‘next’ pointers of intermediate nodes
Assign ‘n’ to ‘next’ of ‘temp’
46. Linked List operations … delete node
Operation Description Pseudo Code
delete_node(key) Deletes node from
list whose ‘data’
value is equal to
‘key’ provided. List
remains in tact
after delete
operation has
executed
Take a node pointer ‘temp’ and point it
to ‘start’
Iterate ‘temp’ through list nodes until
either a node with matching ‘data’ is
found or list ends
If list has ended, nothing happens
If node with ‘data’ equal to ‘key’ was
found at ‘start’, ‘start’ pointer starts
pointing to its ‘next’ node
If node with ‘data’ equal to ‘key’ was
found after ‘start’, list pointers are
adjusted and that node is removed from
list
47. Linked List operations … delete node
No node in Linked List had same value of ‘data’ as of ‘key’ provided to procedure
Linked List remains same, nothing happens
48. Linked List operations … delete node
‘start’ node in Linked List had same value of ‘data’ as of ‘key’ provided to procedure
‘start’ pointer points to next node in list, matching node is removed from list
49. Linked List operations … delete node
A node in Linked List after ‘start’ had same value of ‘data’ as of ‘key’ provided to procedur
Linked List remains intact with ‘data 3’ node removed
50. Linked List Operations … C++ Code
Create two classes i. Node ii. LinkList as their ADT
Node class is simple it just contains two data members i. data (int data type for simplicity) ii.
next (Node pointer) for pointing to next node in list
Create public constructor for Node class
Create setters and getters for Node data members
Node class code is all set
51. Linked List Operations … node class
class Node {
int data;
Node* next;
public:
Node(){data=0;next=0;};
void set_data(int d){this->data=d;};
int get_data(){ return this->data; };
void set_next(Node *n){this->next=n;};
Node* get_next(){return this->next;};
};
52. Linked List Operations … C++ Code
Create class LinkList with a single data member i. start (a node pointer) pointing to head node of
Linked List
Define constructor and operations as discussed earlier
Selected operations code is given as:
Note: implement yourself remaining function belonging to LinkList class
53. Linked List Operations … linklist class
class LinkList{
Node* start;
public:
LinkList();
void add_node(int);
void append_node(int);
int size();
Node* search(int);
void delete_node(int);
void insert(int, int);
void print_all();
};
57. Linked List Operations … main method
int main(int argc, char** argv) {
LinkList list;
list.add_node(2);
list.append_node(10);
list.add_node(7);
list.insert(3,25);
list.print_all();
list.delete_node(30);
list.print_all();
return 0;
}
58. Structure of Link List
Struct{
Int data;
Struct node * link ;
};
Struct node * ptfirst = null; (null = 0)
59. Main Algorithm
Start
Repeat (loop) while true (true = 1)
[menu option]
Write(cout) (“1: Insert ”);
Write (“2: display ”);
Write (“3: Insert first ”);
Write (“4: Insert after ”);
Write (“5: Insert before ”);
Write (“6: Delete ”);
Write (“7: Exite ”);
Write (“Enter option number ”);
Read (cin) option number (option_number)
Select option_number
It include switch case
Option 1
Write (“ Insert value ”);
Read value
Insert (value)
Option 2
60. Insert (value)
[check for empty list]
If ptfirst == NULL ; then
Temp = new node ;
Temp -> link = ptfirst;
Ptfirst = temp;
Else
Ptfirst = temp ;
Repeat while loop (temp != NULL)
Temp = temp -> link;
[End of loop of step 2a]
Temp-> link = new node ;
Temp = temp -> link ;
[End of if-else structure ]
Temp -> data = value;
Temp -> link = NULL;
61. Display();
if ptfirst == NULL then
write(“list is empty”);
return
[End of if structure ]
temp = ptfist;
repeat while (temp != NULL)
◦ write (temp -> data)
◦ Temp -> temp -> link ;
[End of loop]
return ;
Algorithm for inset first
Insert first(value)
[creat a new node ]
Temp = new node;
Temp -> data = value;
Temp -> link = ptfirst;
Ptfirst = temp;
Return;