ds module2
ds module2
UNIT II
ARRAYS
An array is a collection of similar data elements. These data elements have the same data type. The
elements of the array are stored in consecutive memory locations and are referenced by an index (also
known as the subscript). The subscript is an ordinal number which is used to identify an element of
the array.
DECLARATION OF ARRAYS
We have already seen that every variable must be declared before it is used. The same concept holds
true for array variables. An array must be declared before being used. Declaring an array
means specifying the following:
➢ Data type—the kind of values it can store, for example, int, char, float, double.
➢ Name—to identify the array.
➢ Size—the maximum number of values that the array can hold.
Arrays are declared using the following syntax:
type name[size];
When we declare an array, we are just allocating space for its elements; no values are stored in the
array. There are three ways to store values in an array. First, to initialize the array elements during
declaration; second, to input values for individual elements from the keyboard; third, to assign values
to individual elements. The elements of an array can be initialized at the time of declaration, just as
any other variable. When an array is initialized, we need to provide a value for every element in the
array. Arrays are initialized by writing,
type array_name[size]={list of values};
Note that the values are written within curly brackets and every value is separated by a comma. It is
a compiler error to specify more values than there are elements in the array. When we write,
int marks[5]={90, 82, 78, 95, 88};
An array with the name marks is declared that has enough space to store five elements. The first
element, that is, marks[0] is assigned value 90. Similarly, the second element of the array, that is
marks[1], is assigned 82, and so on.
2
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
OPERATIONS ON ARRAYS
There are a number of operations that can be performed on arrays. These operations include:
➢ Traversing an array
➢ Inserting an element in an array
➢ Searching an element in an array
➢ Deleting an element from an array
➢ Merging two arrays
➢ Sorting an array in ascending or descending order
TRAVERSING AN ARRAY
Traversing an array means accessing each and every element of the array for a specific purpose.
Traversing the data elements of an array A can include printing every element, counting the total
number of elements, or performing any process on these elements. Since, array is a linear data structure
(because all its elements form a sequence), traversing its elements is very simple and straightforward.
The algorithm for array traversal is
In Step 1, we initialize the index to the lower bound of the array. In Step 2, a while loop is executed.
Step 3 processes the individual array element as specified by the array name and index value. Step 4
increments the index value so that the next array element could be processed. The while loop in Step
2 is executed until all the elements in the array are processed, i.e., until I is less than or equal to the
upper bound of the array.
Write a program to read and display n numbers using an array.
#include <stdio.h>
#include <conio.h>
int main()
{
3
int i, n, arr[20];
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d",&arr[i]);
}
printf("\n The array elements are ");
for(i=0;i<n;i++)
printf("\t %d", arr[i]);
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The array elements are 1 2 3 4 5
If an element has to be inserted at the end of an existing array, then the task of insertion is quite simple.
We just have to add 1 to the upper_bound and assign the value. Here, we assume that the memory
space allocated for the array is still available. For example, if an array is declared to contain 10
elements, but currently it has only 8 elements, then obviously there is space to accommodate two more
elements. But if it already has 10 elements, then we will not be able to add another element to it.
4
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
Data[] is an array that is declared as int Data[20]; and contains the following
values:
Data[] = {12, 23, 34, 45, 56, 67, 78, 89, 90, 100};
(a) Calculate the length of the array.
(b) Find the upper_bound and lower_bound.
(c) Show the memory representation of the array.
(d) If a new data element with the value 75 has to be inserted, find its position.
(e) Insert a new data element 75 and show the memory representation after the insertion.
Solution
(a) Length of the array = number of elements
Therefore, length of the array = 10
(b) By default, lower_bound = 0 and upper_bound = 9
(c)
(d) Since the elements of the array are stored in ascending order, the new data element will be
stored after 67, i.e., at the 6th location. So, all the array elements from the 6 th position will be
moved one position towards the right to accommodate the new value
(e)
In the algorithm given in Fig. 3.14, in Step 1, we first initialize I with the total number of elements in
the array. In Step 2, a while loop is executed which will move all the elements having an index greater
than POS one position towards right to create space for the new element. In Step 5, we increment the
total number of elements in the array by 1 and finally in Step 6, the new value is inserted at the desired
position.
Write a program to insert a number at a given location in an array.
#include <stdio.h>
#include <conio.h>
int main()
{
int i, n, num, pos, arr[10];
clrscr();
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d", &arr[i]);
}
printf("\n Enter the number to be inserted : ");
scanf("%d", &num);
printf("\n Enter the position at which the number has to be added : ");
scanf("%d", &pos);
for(i=n–1;i>=pos;i––)
arr[i+1] = arr[i];
arr[pos] = num;
n = n+1;
printf("\n The array after insertion of %d is : ", num);
for(i=0;i<n;i++)
printf("\n arr[%d] = %d", i, arr[i]);
getch();
return 0;
}
Output
6
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Enter the number to be inserted : 0
Enter the position at which the number has to be added : 3
The array after insertion of 0 is :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 0
arr[4] = 4
arr[5] = 5
Deleting an element from an array means removing a data element from an already existing array. If
the element has to be deleted from the end of the existing array, then the task of deletion is quite
simple. We just have to subtract 1 from the upper_bound. Figure 3.15 shows an algorithm to delete an
element from the end of an array.
Example: Data [] is an array that is declared as int Data[10]; and contains the following values:
Data[] = {12, 23, 34, 45, 56, 67, 78, 89, 90, 100};
(a) If a data element with value 56 has to be deleted, find its position.
(b) Delete the data element 56 and show the memory representation after the deletion.
Solution
(a) Since the elements of the array are stored in ascending order, we will compare the value that
has to be deleted with the value of every element in the array. As soon as VAL = Data[I], where
7
I is the index or subscript of the array, we will get the position from which the element has to
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
be deleted. For example, if we see this array, here VAL = 56. Data[0] = 12 which is not equal
to 56. We will continue to compare and finally get the value of POS = 4.
(b)
The algorithm DELETE will be declared as DELETE(A, N, POS). The arguments are:
(a) A, the array from which the element has to be deleted
(b) N, the number of elements in the array
(c) POS, the position from which the element has to be deleted
printf("\nEnter the position from which the number has to be deleted : ");
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
scanf("%d", &pos);
for(i=pos; i<n–1;i++)
arr[i] = arr[i+1];
n––;
printf("\n The array after deletion is : ");
for(i=0;i<n;i++)
printf("\n arr[%d] = %d", i, arr[i]);
getch();
return 0;
}
Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
Enter the position from which the number has to be deleted : 3
The array after deletion is :
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 5
MULTIDIMENSIONAL ARRAYS
A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in
tabular form. Data in multidimensional arrays is generally stored in row-major order in the memory.
Examples:
Two dimensional array: int two_d[10][20];
Three dimensional array: int three_d[10][20][30];
PARALLEL ARRAYS
Parallel arrays are a group of arrays of the same size. Each element in each array at the same index
corresponds to a different characteristic of the same subject of interest.
In the example below, we store the name and age of five persons in two different arrays.
roll_no = {1, 2, 3, 4, 5}
marks = {25, 20, 18, 30, 32}
The following is a program that demonstrates parallel arrays.
Example: Parallel Array
#include<stdio.h>
int main() {
int max = 0, index = 0, i, n = 5;
int roll_no[] = {1, 2, 3, 4, 5};
int marks[] = {25, 20, 32, 30, 18};
for (int i = 0; i < n; i++) {
if (marks[i] > max) {
max = marks[i];
index = i;
}
}
printf("Roll no %d has highest marks", roll_no[index]);
return 0;
}
Output
APPLICATIONS OF ARRAYS
Arrays are frequently used in C, as they have a number of useful applications. These applications are
• Arrays are widely used to implement mathematical vectors, matrices, and other kinds of
10
rectangular tables.
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
Sparse matrix is a matrix that has large number of elements with a zero value. In order to efficiently
utilize the memory, specialized algorithms and data structures that take advantage of the sparse
structure should be used. If we apply the operations using standard matrix structures and algorithms
to sparse matrices, then the execution will slow down and the matrix will consume large amount of
memory. Sparse data can be easily compressed, which in turn can significantly reduce memory usage.
In the above figure, we can observe a 5x4 sparse matrix containing 7 non-zero elements and 13 zero
elements. The above matrix occupies 5x4 = 20 memory space. Increasing the size of matrix will
increase the wastage space.
Consider a polynomial with two variables: 2x2+5xy+y2. The array representation of the polynomial is
given below:
2 2 0 5 1 1 1 0 2
Index 0 stores the coefficient of the first term, index 1 stores the exponent of the variable x and index
2 stores the exponent of the variable y in the first term. The process is repeated for the remaining terms
in the polynomial.
LINKED LISTS
A linked list, in simple terms, is a linear collection of data elements. These data elements are called
nodes. Linked list is a data structure which in turn can be used to implement other data structures.
Thus, it acts as a building block to implement data structures such as stacks, queues, and their
variations. A linked list can be perceived as a train or a sequence of nodes in which each node contains
one or more data fields and a pointer to the next node.
Advantages of linked lists:
Linked lists have many advantages. Some of the very important advantages are:
1. Linked lists are dynamic data structures. i.e., they can grow or shrink during the execution
of a program.
2. Linked lists have efficient memory utilization. Here, memory is not preallocated. Memory
is allocated whenever it is required and it is de-allocated (removed) when it is no longer needed.
3. Insertion and Deletions are easier and efficient. Linked lists provide flexibility in inserting
a data item at a specified position and deletion of the data item from the given position.
4. Many complex applications can be easily carried out with linked lists.
Disadvantages of linked lists:
1. It consumes more space because every node requires a additional pointer to store address of
the next node.
2. Searching a particular element in list is difficult and also time consuming.
12
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
In Figure, we can see a linked list in which every node contains two parts, an integer and a pointer
to the next node. The left part of the node which contains data may include a simple data type, an
array, or a structure. The right part of the node contains a pointer to the next node (or address of the
next node in sequence). The last node will have no next node connected to it, so it will store a special
value called NULL. In Figure, the NULL pointer is represented by X. While programming, we usually
define NULL as –1. Hence, a NULL pointer denotes the end of the list. Since in a linked list, every
node contains a pointer to another node which is of the same type, it is also called a self-referential
data type.
we can implement a linked list using the following code:
struct node
{
int data;
struct node *next;
};
data will store the information part and next will store the address of the next node in sequence
Array elements store in a contiguous memory Linked list elements can be stored anywhere in
location. the memory or randomly stored.
Array works with a static memory. Here static The Linked list works with dynamic memory.
memory means that the memory size is fixed Here, dynamic memory means that the memory
and cannot be changed at the run time. size can be changed at the run time according to
our requirements.
13
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
Array elements are independent of each other. Linked list elements are dependent on each
other. As each node contains the address of the
next node so to access the next node, we need to
access its previous node.
Array takes more time while performing any Linked list takes less time while performing any
operation like insertion, deletion, etc. operation like insertion, deletion, etc.
Accessing any element in an array is faster as Accessing an element in a linked list is slower as
the element in an array can be directly accessed it starts traversing from the first element of the
through the index. linked list.
In the case of an array, memory is allocated at In the case of a linked list, memory is allocated
compile-time. at run time.
Memory utilization is inefficient in the array. Memory utilization is efficient in the case of a
For example, if the size of the array is 6, and linked list as the memory can be allocated or
array consists of 3 elements only then the rest deallocated at the run time according to our
of the space will be unused. requirement.
In memory the linked list is stored in scattered cells (locations). The memory for each node is allocated
dynamically means as and when required. So the Linked List can increase as per the user wish and the
size is not fixed, it can vary. Suppose first node of linked list is allocated with an address 1008. Its
graphical representation looks like the figure shown below:
Suppose next node is allocated with an address with an address 10,s the list become,
14
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
• Creation.
• Insertion.
• Deletion.
• Traversing.
Creating a singly linked list starts with creating a node. Sufficient memory has to be allocated for
creating a node. The information is stored in the memory, allocated by using the malloc() function.
After allocating memory for the structure of type node, the information for the item (i.e., data) has to
be read from the user, set next field to NULL and finally returns the address of the node.
struct node
{
int data;
struct node *next;
};
node* newnode;
newnode = (node *) malloc(sizeof(node));
15
Algorithm
struct node
{
int data;
struct node *next;
};
struct node *head = NULL;
newNode->next = *head;
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
Example
Input
50
Output
Input
10
Output
Algorithm
17
2. Create a new node with the given data. And make the new node => next as NULL.
(Because the new node is going to be the last node.)
3. If the head node is NULL (Empty Linked List), make the new node as the head.
4. If the head node is not null, (Linked list already has some elements), find the last node.make the
last node => next as the new node.
struct node
{
int data;
struct node *next;
};
struct node *head = NULL;
4. Otherwise, find the last node and set last node => new node
The last node of a linked list has the reference pointer as NULL. i.e. node=>next = NULL.
To find the last node, we have to iterate the linked till the node=>next != NULL.
Pseudocode
while(node->next != NULL)
{
node = node->next;
}
After that, we have to make the last node-> next as the new node. i.e. last node->next = new node;
while(lastNode->next != NULL)
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
{
lastNode = lastNode->next;
}
//add the newNode at the end of the linked list
lastNode->next = newNode;
}
}
Example
Input
20
Output
10 30 NULL
Algorithm
make the head node points to the second node and free its memory.
2. Otherwise,
From the current node, check whether the next node has the given key
else, update the current node to the next and do the above process (from step 2) till the last node.
current->next = current->next->next;
free(temp);
break;
}
//Otherwise, move the current node and proceed
else
current = current->next;
}
}
}
Example
Input
20
Output
Search Found
Algorithm
3. If the program execution comes out of the loop (the given key is not present in the linked list), return
-1.
Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous
as well as the next node in the sequence. Therefore, in a doubly linked list, a node consists of three
parts: node data, pointer to the next node in sequence (next pointer) , pointer to the previous node
(previous pointer). A sample node in a doubly linked list is shown in the figure.
A doubly linked list containing three nodes having numbers from 1 to 3 in their data part, is shown in
the following image.
The prev part of the first node and the next part of the last node will always contain null indicating
end in each direction.
In a singly linked list, we could traverse only in one direction, because each node contains address of
the next node and it doesn't have any record of its previous nodes. However, doubly linked list
overcome this limitation of singly linked list. Due to the fact that, each node of the list contains the
24
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
address of its previous node, we can find all the details about the previous node as well by using the
previous address stored inside the previous part of each node.
Memory Representation of a doubly linked list is shown in the following image. Generally, doubly
linked list consumes more space for every node and therefore, causes more expansive basic operations
such as insertion and deletion. However, we can easily manipulate the elements of the list since the
list maintains pointers in both the directions (forward and backward). In the following image, the first
element of the list that is i.e. 13 stored at address 1. The head pointer points to the starting address 1.
Since this is the first element being added to the list therefore the prev of the list contains null. The
next node of the list resides at address 4 therefore the first node contains 4 in its next pointer.
We can traverse the list in this way until we find any node containing null or -1 in its next part.
Pushing a node to a doubly-linked list is similar to pushing a node to a linked list, but extra work is
required to handle the pointer to the previous node.
Let's add a node with value 6 at the beginning of the doubly linked list we made above.
1. Create a new node
• allocate memory for newNode
• assign the data to newNode.
Let's add a node with value 6 after node with value 1 in the doubly linked list.
3. Set the prev pointer of new node and the next node
• assign the value of prev of next node to the prev of newNode
• assign the address of newNode to the prev of next node
Let's add a node with value 6 at the end of the doubly linked list.
2. Set prev and next pointers of new node and the previous node
If the linked list is empty, make the newNode as the head node. Otherwise, traverse to the end of the
doubly linked list and
29
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
}
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
// if the linked list is not empty, traverse to the end of the linked list
while (temp->next != NULL)
temp = temp->next;
// now, the last node of the linked list is temp
// point the next of the last node (temp) to newNode.
temp->next = newNode;
// assign prev of newNode to temp
newNode->prev = temp;
}
Similar to insertion, we can also delete a node from 3 different positions of a doubly linked list.
Suppose we have a double-linked list with elements 1, 2, and 3.
Finally, free the memory of del_node. And, the linked will look like this
31
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
If del_node is an inner node (second node), we must have to reset the value of next and prev of the
nodes before and after the del_node.
For the node before the del_node (i.e. first node)
Assign the value of next of del_node to the next of the first node.
For the node after the del_node (i.e. third node)
Assign the value of prev of del_node to the prev of the third node.
Finally, we will free the memory of del_node. And, the final doubly linked list looks like this.
if (del_node->prev != NULL)
del_node->prev->next = del_node->next;
32
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
In this case, we are deleting the last node with value 3 of the doubly linked list.
Here, we can simply delete the del_node and make the next of node before del_node point
to NULL.
if (del_node->prev != NULL)
del_node->prev->next = del_node->next;
Each node consists of a data value Each node consists of a data value, a pointer to the
and a pointer to the next node. next node, and a pointer to the previous node.
Circular Linked List is a variation of Linked list in which the first element points to the last element
and the last element points to the first element. Both Singly Linked List and Doubly Linked List can
be made into a circular linked list.
In singly linked list, the next pointer of the last node points to the first node.
In doubly linked list, the next pointer of the last node points to the first node and the previous pointer
of the first node points to the last node making the circular in both directions.
Let's see how we can represent a circular linked list on an algorithm/code. Suppose we have a linked
list:
34
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
struct Node {
int data;
struct Node * next;
};
Each struct node has a data item and a pointer to the next struct node.
Now we will create a simple circular linked list with three items to understand how this works.
/* Initialize nodes */
struct node *last;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
/* Connect nodes */
one->next = two;
two->next = three;
35
three->next = one;
Page
Data Structure
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES B.Sc./BCA STUDY MATERIALS
Using C
Let's add a node with value 6 at different positions of the circular linked list we made above. The first
step is to create a new node.
• store the address of the current first node in the newNode (i.e. pointing the newNode to the
current first node)
• point the last node to newNode (i.e making newNode as head)
• store the address of the head node to next of newNode (making newNode the last node)
• point the current last node to newNode
• make newNode as the last node
A header linked list is a type of linked list that has a header node at the beginning of the list. In a
header linked list, HEAD points to the header node instead of the first node of the list.
The header node does not represent an item in the linked list. This data part of this node is generally
used to hold any global information about the entire linked list. The next part of the header node points
to the first node in the list.
39
Page