You are on page 1of 55

Data Structure

Using C
Why Data Structure?
• The data structure name indicates itself that organizing the data in memory.
There are many ways of organizing the data in the memory as we have already
seen one of the data structures, i.e., array in C language.
• The data structure is not any programming language like C, C++, java, etc. It is a
set of algorithms that we can use in any programming language to structure the
data in the memory.
• To structure the data in memory, 'n' number of algorithms were proposed, and all
these algorithms are known as Abstract data types. These abstract data types are
the set of rules.
Need of Data Structures
• As applications are getting complexed and amount of data is increasing day by day, there may
arrise the following problems:
• Processor speed: To handle very large amout of data, high speed processing is required, but as
the data is growing day by day to the billions of files per entity, processor may fail to deal with
that much amount of data.
• Data Search: Consider an inventory size of 106 items in a store, If our application needs to search
for a particular item, it needs to traverse 106 items every time, results in slowing down the search
process.
• Multiple requests: If thousands of users are searching the data simultaneously on a web
server, then there are the chances that a very large server can be failed during that process
• in order to solve the above problems, data structures are used. Data is organized to form a
data structure in such a way that all items are not required to be searched and required data
can be searched instantly.
Difference between data type and data structure
• A data type is the most basic and the most common classification of data. It is
this through which the compiler gets to know the form or the type of
information that will be used throughout the code.
• So basically data type is a type of information transmitted between the
programmer and the compiler where the programmer informs the compiler
about what type of data is to be stored and also tells how much space it
requires in the memory. Some basic examples are int, string etc. It is the type
of any variable used in the code.
• A data structure is a collection of different forms and different types of data
that has a set of specific operations that can be performed. It is a collection of
data types. It is a way of organizing the items in terms of memory, and also the
way of accessing each item through some defined logic. Some examples of data
structures are array, stacks, queues, linked lists, binary tree and many more.
Introduction
• Data Structure can be defined as the group of data elements which provides an
efficient way of storing and organizing data in the computer so that it can be used
efficiently.
• Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc. Data
Structures are widely used in almost every aspect of Computer Science i.e.
Operating System, Compiler Design, Artifical intelligence, Graphics and many
more.
Types of Data Structures
• There are two types of data structures:
• Primitive data structure
• Non-primitive data structure
• Primitive Data structure
• The primitive data structures are primitive data types. The int, char, float,
double, and pointer are the primitive data structures that can hold a single
value.
• Non-Primitive Data structure
• The non-primitive data structure is divided into two types:
• Linear data structure
• Non-linear data structure
Operations on data structure
• The most commonly used operation on data structure are broadly
categorized into following types:
• Create
• Insertion
• Selection
• Updating
• Searching
• Sorting
• Merging
• Destroy or Delete
Advantages of Data Structures
• Efficiency: Efficiency of a program depends upon the choice of data structures.
For example: suppose, we have some data and we need to perform the search
for a perticular record. In that case, if we organize our data in an array, we will
have to search sequentially element by element. hence, using array may not be
very efficient here. There are better data structures which can make the search
process efficient like binary search tree or hash tables.
• Reusability: Data structures are reusable, i.e. once we have implemented a
particular data structure, we can use it at any other place. Implementation of
data structures can be compiled into libraries which can be used by different
clients.
• Abstraction: Data structure is specified by the ADT which provides a level of
abstraction. The client program uses the data structure through interface only,
without getting into the implementation details.
Array
• An array is a group of consective memory locations with same name
and datatype.
• An array is a collection of items stored at contiguous memory locations.
• Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc.
• The idea is to store multiple items of the same type together. This makes it easier
to calculate the position of each element by simply adding an offset to a base
value, i.e., the memory location of the first element of the array (generally
denoted by the name of the array).
8
i=6
arr[i+1]=arr[i] ()
i--= 5;
Arr[i+1]=arr[i]=> arr[6]=arr[5]

2 4 8 6 9 12 7 3
0 1 2 3 4 5 6 7 8 9
Contd..
• Simple variable is a single memory location with unique name and a
type. But an Array is collection of different adjacent memory
locations. All these memory locations have one collective name and
type.
• The memory locations in the array are known as elements of array.
The total number of elements in the array is called length.
• The elements of array is accessed with reference to its position in
array, that is call index or subscript.
Advantages of Array

• Array provides the single name for the group of variables of the same
type therefore, it is easy to remember the name of all the elements of
an array.
• Traversing an array is a very simple process, we just need to
increment the base address of the array in order to visit each element
one by one.
• Any element in the array can be directly accessed by using the index.
Types of Arrays:

• One-Dimensional Array
• Two-Dimensional Array
• Multi-Dimensional Array
One-D array Intialization

• The process of assigning values to array elements at the time of array


declaration is called array initialization.
• Syntax:
data_type identifier[length]={ List of values };
e.g: int marks[5]={70,54,82,96,49};
• Data _type: Data type of values to be stored in the array.
• Identifier: Name of the array.
• Length: Number of elements
• List of values: Values to initialize the array. Initializing values must be constant
Array of an element of an array say “A[ I ]” is calculated using the following formula:
Address of A [ I ] = B + W * ( I – LB )
Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found
LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)
Q: B.A=100, A[10…..40], E[14]=?,W=2;
100 102 104 106 108 110 112 ……

10 11 12 13 14 15 16 ….

B+W*[I-LB]
100+2[14-10]
108
Example:
• Given the base address of an array B[1300…..1900] as 1020 and size of
each element is 2 bytes in the memory. Find the address of B[1700].
Solution:
• The given values are: B = 1020, LB = 1300, W = 2, I = 1700
• Address of A [ I ] = B + W * ( I – LB )
• = 1020 + 2 * (1700 – 1300)
= 1020 + 2 * 400
= 1020 + 800
= 1820 [Ans]
C Multidimensional Arrays
In C programming, you can create an array of arrays. These
arrays are known as multidimensional arrays. For example,

float x[3][4];

Here, x is a two-dimensional (2d) array. The array can hold 12


elements. You can think the array as a table with 3 rows and
each row has 4 columns.
Address Calculation in Double (Two) Dimensional Array: A[1..3][1…4]
• While storing the elements of a 2-D array in memory, these are allocated contiguous memory locations. Therefore,
a 2-D array must be linearized so as to enable their storage. There are two alternatives to achieve linearization:
Row-Major and Column-Major.I=1,J=2
• Array size= M* N
• ADDR[1][J]
• = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
• 100+2[4(1-0)+(2-0)]=112
• Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as given:
(1) Row Major System (2) Column Major System. Consider array size as:A[M][N]
• Row Major System:
• The address of a location in Row Major System is calculated using the following formula:
• Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
• Column Major System:
• The address of a location in Column Major System is calculated using the following formula:
• Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]
• Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix
Array of size A[M][N], find address Of
element at index T[i][j]:
• Consider index is starting from 0:

ROW MAJOR
A [ I ][ J ] = B + W * [ N *I +J]

COLUMN MAJOR
A[I][J]= B + W*[M*J+I]
Q1. T[20][12],
B.A=100,CHARACTER,ARRAY[100][200]
• 100+1[200*20+12]=100+4012=4112
• =100+1[100*12+20]=1220+100=1320

• Q2. Given an array [6][7] of integers. Calculate address of element T[4,6], where BA=900.
A [ I ][ J ] = B + W * [ N *I +J]
ROW MAJOR =900+4[7(4)+6]=1036
COLUMN MAJOR= 900+4[6*6+4]=1060
Array of size A[20][30], T[10][20], B.A=100,
W=2
• A[M][N], M=20, N=30
• ROW MAJOR:
• 100+2(30*10+20)=740
• COULMN MAJOR:
• 100+2(20*20+10)=920
A[0….10][0….25]
X[5][24], B.A=1500, W=1

• M=10-0+1=11
• N=25-0+1=26

• 3*6= I*N+J
100 1 2 3 4 5

dfgdf
A[3][2]
• Important : Usually number of rows and columns of a matrix are given
( like A[20][30] or A[40][60] ) but if it is given as A[Lr- – – – – Ur, Lc- – – –
– Uc]. In this case number of rows and columns are calculated using the
following methods:

• Number of rows (M) will be calculated as = (Ur – Lr) + 1


Number of columns (N) will be calculated as = (Uc – Lc) + 1
• And rest of the process will remain same as per requirement (Row Major
Wise or Column Major Wise).
• Number of rows (M) will be calculated as = (Ur – Lr) + 1
Number of columns (N) will be calculated as = (Uc – Lc) + 1
• And rest of the process will remain same as per requirement (Row Major
Wise or Column Major Wise).
Examples:

• An array X [-15……….10, 15……………40] requires one byte of storage. If beginning location is


1500 determine the location of X [5][20].
Solution:
• As you see here the number of rows and columns are not given in the question. So they are
calculated as:
• Number or rows say M = (Ur – Lr) + 1 = [10 – (- 15)] +1 = 26
Number or columns say N = (Uc – Lc) + 1 = [40 – 15)] +1 = 26
(i) Column Major Wise Calculation of above equation
The given values are: B = 1500, W = 1 byte, I = 5, J = 20, Lr = -15, Lc = 15, M = 26
Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ]
= 1500 + 1 * [(5 – (-15)) + 26 * (20 – 15)] = 1500 + 1 * [20 + 26 * 5] = 1500 + 1 * [150] =
1650 [Ans]
(ii) Row Major Wise Calculation of above equation
The given values are: B = 1500, W = 1 byte, I = 5, J = 20, Lr = -15, Lc = 15, N = 26
Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]
= 1500 + 1* [26 * (5 – (-15))) + (20 – 15)] = 1500 + 1 * [26 * 20 + 5] = 1500 + 1 * [520 + 5] =
1500 + 525
= 2025 [Ans]
• A matrix D[15][13] is stored in memory with each element requiring 4
bytes of storage . If the base address at d[1][1] is 2500, determine the
address at D[8][7]?
• Answer :
• ROW MAJOR:
• The given values are B=2500,W=4 bytes , I=8, J=7 , Lr=1, Lc=1, M=15,
N=13. Address of D[8][7]=B+[(I-Lr)*N+(J-Lc)]*W = 2500+[(8-1)*13+(7-
1)]*4 = 2500+[91+6]*4 = 2500+388= 2888
• a) Let A be a matrix of 15 rows and 20 columns with the base address
2146, if each element of the array occupies 8 bytes, find the address
of A[8][10], when the matrix is arranged: 1) Row major wise and 2)
Column major wise.
• Row major=2146+8(20*8+10)
• b) Each element of the array A[20][10]requires two bytes of storage. If
the address of A[6][8] is 4000, find the base address at A[0][0] when
the array is arranges Row Major Wise.
• 4000=B+2(10*6+8)
• a) A two-dimensional array defined as X[3…..6, -2……2] requires 2 bytes of storage space for each element.
If the array is stored in Row-Major Wise, determine the address of X[5][1], given the base address is 1200.
• I=5,J=1,B=1200, W=2, M=4, N=5
• 1200+2[5(5-3)+(1-(-2))]=1226

• b) A matrix M[15][10] is stored in the memory with each element requires 4 bytes of storage . if the
address at B[1][y] is 716 and the address at B[8][5] is 1000. Determine the value of ‘y’, when the matrix is
stored in Row Major Wise.
• =M=15,N=10,W=4,
• 716=B+4[10*1+Y] …….1 => 716-40-4Y=B
• 1000=B+4[10*8+5] ………2 => 1000-340=B
• 1000-340=716-40-4Y=>-16=-4Y

From the second equation B=660.


• 56=40+4Y
• Y=4
2D array example
// C program to store temperature of two cities of a week
and display it.
printf("\nDisplaying values: \n\n");
#include <stdio.h>
for (int i = 0; i < CITY; ++i)
int CITY = 2;
{
int WEEK = 7;
for (int j = 0; j < WEEK; ++j)
int main()
{
{
printf("City %d, Day %d = %d\n", i + 1, j + 1, temperature[i]
int temperature[CITY][WEEK];
[j]);
for (int i = 0; i < CITY; ++i)
}
{
}
for (int j = 0; j < WEEK; ++j)
return 0;
{
}
printf("City %d, Day %d: ", i + 1, j + 1);
scanf("%d", &temperature[i][j]);
}
}
Accessing element of array

• Individual Element:
Array_name[index];
• Using Loop:
int marks[5];
for(int i=0;i<=4;i++)
marks[i]=i;
Searching In Array

• Searching is a process of finding the required data in the array.


• Searching becomes more important when the length of the array is
very large.
• There are two techniques to searching elements in array as follows:
• Sequential search
• Binary search
Basic Operations

Following are the basic operations supported by an array.


• Traverse − print all the array elements one by one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given index or by the
value.
The original array elements are :
Traversing LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
int LA[] = {1,3,5,7,8}; LA[4] = 8
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
Insertion Operation

• Insert operation is to insert one or more data elements into an array.


Based on the requirement, a new element can be added at the
beginning, end, or any given index of array.
• Here, we see a practical implementation of insertion operation, where
we add data at the end of the array.
5 6 8 1 4

5 6 9 8 1
INSERTION
printf("Enter the index where you want to insert new
element: ");
scanf("%d", &pos);

printf("Enter the value to insert: ");


#include<stdio.h>
scanf("%d", &value);
int main()
{ for(c = n-1; c >= pos; c--)
int array[100], pos, c, n, value; array[c+1] = array[c];

printf("Enter number of elements in array:"); array[pos] = value;


scanf("%d", &n);
printf("\nResultant array is: ");
printf("Enter %d elements\n", n);
for(c = 0; c < n; c++) for(c = 0; c <= n; c++)
scanf("%d", &array[c]); printf("%d ", array[c]);

return 0;
}
Deletion Operation

• Deletion refers to removing an existing element from the array and re-
organizing all elements of an array.
• Deletion refers to removing an existing element from the array and re-
organizing all elements of an array.
Deletion
Deletion
#include<stdio.h> if (pos >= n+1)
int main() printf("Deletion not possible.\n");
else
{
{
int array[20], pos, i, n; for (i =pos-1; i<n-1; i++)
printf("Enter number of elements in array"); array[i] = array[i+1];
scanf("%d", &n);
printf("Enter %d elements\n", n); printf("Resultant array:\n");
for (i = 0; i<n-1; i++)
for (i = 0; i<n; i++)
printf("%d\n", array[i]);
scanf("%d", &array[i]]); }
printf("Enter the location where you wish to
delete element\n"); return 0;
scanf("%d", &pos); }
Search Operation

• Linear search
• Binary search
2 4 5 2 3 6 5 2

2 4 5 3 6
Sequential Search

• Sequential search is also known as linear or serial search. It follows


the following step to search a value in array.
• Visit the first element of array and compare its value with required
value.
• If the value of array matches with the desired value, the search is
complete.
• If the value of array does not match, move to next element an repeat
same process.
Search, insert and delete in an unsorted array
• In an unsorted array, the search operation can be performed by linear
traversal from the
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;
Binary Search
• Binary search is a quicker method of searching for value in the array. Binary
search is very quick but it can only search an sorted array. It cannot be applied on an
unsorted array.
• It locates the middle element of array and compare with desired number.
• If they are equal, search is successful and the index of middle element is
returned.
• If they are not equal, it reduces the search to half of the array.
• If the search number is less than the middle element, it searches the first half of
array.
• Otherwise it searches the second half of the array. The process continues until
the required number is found or loop completes without successful search.
• Note: refer program
0 1 2 3 4 5 6 7 8

2 4 7 9 10 15 18 23 29

H L=5 M=6 L H=8


H=5

X=15
M=L+H/2=4
A[M]=X
A[M]>X, 18>15
H=M-1

ELSE A[M]<X , 10<15


L=M+1
M=6
while (first <= last) {
if (array[middle] < search)
int main()
first = middle + 1;
{
else if (array[middle] == search) {
int c, first, last, middle, n, search,
printf("%d found at location %d.\n", search, middle+1);
array[100];
break;
printf("Enter number of elements\n");
}
scanf("%d", &n);
else
printf("Enter %d integers\n", n); last = middle - 1;
for (c = 0; c < n; c++) middle = (first + last)/2;
scanf("%d", &array[c]); }
printf("Enter value to find\n"); if (first > last)
scanf("%d", &search); printf("Not found! %d isn't present in the list.\n", search);
first = 0; return 0;
last = n - 1; }
middle = (first+last)/2;
SEARCHING
#include<stdio.h>
int main() if(flag==0)
{ int a[20],i,n,m,flag=0; printf("not present");
printf("insert number of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
return 0;
printf("insert the element u want to search:");
}
scanf("%d",&m);
for(i=0;i<n;i++)
{ if(m==a[i])
{printf("value is present at index %d",i);
flag=1;
break;}
}
MAXIMUM ELEMENT
#include<stdio.h>
int main()
{ int a[20],i,n,max;
printf("insert number of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
max=a[0];
for(i=1;i<n;i++)
{ if(a[i]>max)
max=a[i];
}
printf("max value is %d",max);
return 0;
}
Matrix multiplication
#include<stdio.h> cout<<"Enter elements of matrix 2: "<<endl;
#include<iostream> for(i=0; i<r2; ++i)
using namespace std; for(j=0; j<c2; ++j)
int main() {
{ cin>>b[i][j];
int a[10][10], b[10][10], result[10][10], r1, c1, r2, c2, i, j, k; }
for(i=0; i<r1; ++i)
cout<<"Enter rows and column for first matrix: "; for(j=0; j<c2; ++j)
cin>>r1>>c1; {
cout<<"Enter rows and column for second matrix: "; result[i][j]=0;
cin>>r2>>c2; }
if(c1!=r2){ for(i=0; i<r1; ++i)
cout<<"cant multiply"; for(j=0; j<c2; ++j)
} for(k=0; k<c1; ++k)
else{ {
cout<<"Enter elements of matrix 1:"; result[i][j]+=a[i][k]*b[k][j];
for(i=0; i<r1; ++i) }
for(j=0; j<c1; ++j) cout<<"Output Matrix:";
{ for(i=0; i<r1; ++i)
cin>> a[i][j]; {
} for(j=0; j<c2; ++j)
{
cout<< result[i][j];

}cout<<endl;}
}return 0;
}
Merge two sorted arrays while (i < m && j < n) while (i < m)
{ {
#include <stdio.h> if (array1[i] < array2[j]) array3[k] = array1[i];
{ i++;
void main() k++;
array3[k] = array1[i];
{ }
i++;
int array1[10], array2[10], array3[20], m, n, i, j, k=0;
} printf("\n After merging: \n");
printf("\n Enter size of array Array 1: "); else for (i = 0; i < m + n; i++)
scanf("%d", &m); { {
array3[k] = array2[j];
printf("\n%d", array3[i]);
printf("\n Enter sorted elements of array 1: \n");
}
for (i = 0; i < m; i++) j++;
} }
scanf("%d", &array1[i]);
k++;
printf("\n Enter size of array 2: ");
}
scanf("%d", &n); while (j < n)
printf("\n Enter sorted elements of array 2: \n"); {
for (i = 0; i < n; i++) array3[k] = array2[j];
scanf("%d", &array2[i]); j++;
k++;
i = 0;
}
j = 0;
2,3,4,2,3,5,3,3,4
2,3,4,5

You might also like