MCA Data Structures With Algorithms 01
MCA Data Structures With Algorithms 01
01
D
E
Introduction to Data Structures
V
R
E
S
Names of Sub-Units
E
Introduction to Data Structure: Classification of Data Structures, Data Structure Operations, Basic
R
Concepts of Pointers, Structures and Union, Algorithm, Characteristics of the Algorithm.
T
Overview
H
This unit begins by discussing about the concept of Stacks. Next, the unit discusses the Operations
of stack, representing stack using static arrays. Further the unit explains the Dynamic array for
IG
representing stack. Towards the end, the unit discusses the application of stack.
R
Learning Objectives
Y
Learning Outcomes
D
aa Explore the characteristics of algorithm
E
Pre-Unit Preparatory Material
V
aa https://www.studytonight.com/data-structures/introduction-to-data-structures
R
aa https://www.geeksforgeeks.org/data-structures/
E
1.1 Introduction
S
A data structure is a defined format for managing, assessing, retrieving and storing data. Data
E
structures make it easy for users to work with the data they require in different ways. data structure
is designed or selected for storing the data to use different algorithms, in Computer programming. The
R
basic algorithm operations are integrated into the design of the data structure. Each data structure has
information related to the data values, the association between data and functions which are applied
to the data.
T
Data structure is a way to store and organise data in computer memory so that data can be used
IG
effectively later. It can be arranged in various ways, such as the mathematical or logical model for
the specific organisation of data is known as data structure. In general, the choice of the data model is
based on two considerations. First, it should be defined structure to exhibit the relationships of data in
the real world. Secondly, the structure should be simple so that one can able to process the data when
R
required. Data structure is the process of arranging data and its functions.
Y
The needs of data structures contain the following: efficiency, re-usability, and invisibility. Data structure
offers a means of establishing, handling, and storage data efficiently. It also comprises the collection of
O
2
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY
D
structure is classified into the primitive and non-primitive data structures are as follows:
zz Primitive data structures: Primitive data structures are the basic data structures that can
E
be operated on machine and data instructions directly. It can be defined by the programming
languages. Primitive data types are integer, floating point number, real and pointer.
V
zz Non primitive data structures: Non primitive data structures are the data structures that can be
derived from primitive data structures. Non primitive data structures are stacks, graphs, trees and
R
linked lists
E
1.5 Data structure Operations
S
Data Structure is well-defined as a mathematical or logical model to store data and perform operation
on the stored data. The operations are the purposes using which the data can be managed. All the data
E
structure has some common operations to manipulate data and process it for the user. The operation
R
on data structures are as follows:
zz Traversing: Each data structure has a set of data elements. Traversing refers to visiting each
element of data structure to manage operations such as searching or sorting.
T
For example: if we want to compute the average of marks secured by students in five different
subjects. We need to traverse the array of marks and compute the total sum. We will divide that sum
H
zz Insertion: It is the process of adding elements to the data structures at any location. n is the size of
the data structure and we can insert n-1 data elements into it.
zz Deletion: The phenomenon of removing the element from the data structure is known as deletion.
R
We delete the element from the data structure at any location. Underflow condition occurs when
trying to delete an element from the empty data structure.
Y
zz Searching: It refers to detecting the location of the element in the data structure is known as
searching. Linear search and binary search are the two algorithms to evaluate searching.
P
zz Sorting: It refers to the phenomenon of organising the data structure in a particular order is called
sorting. Several algorithms can be used to evaluate sorting. Example: selection sort, insertion sort
O
zz Merging: The two lists such as List X and List Y of size of K and L, respectively. They have the identical
type of elements combined to generate the third list, List Z of size (K+L). This phenomenon is known
as merging.
1.6 Pointers
A Pointer is a derived data type that stores the address of another variable. A Pointer contains memory
addresses as their values. Pointers can be used to assign, access, and manipulate data values stored in
the memory allotted to a variable since it can access the memory address of that variable.
3
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
D
is declaring pointers is given below:
zz Declaring pointers: Pointer declarations is * operation. The syntax is,
E
int a=12;
int *ptr; //pointer declaration
V
pte =&a; // pointer initialization
from the given example, p is a pointer and its type is termed as a pointer to int, it stores the address
R
of integer variable.
E
1.6.2 Pointer with functions
S
You can use the function pointers to eliminate code redundancy. Example: qsort() is used to sort arrays in
descending or ascending order concerning an array of structures. By using void pointers and function
E
pointers, it is significant to use qsort for any type of data type. Function pointers are the pointers
(variable) that refer to the address of the function. It will call functions at run time. The functions are
R
evaluated at run time is known as late binding.
Syntax:
T
Function pointer refers to point to function with a particular sign. All these functions have the same
parameters and return type. Function pointer and function whose address is referred to have the same
sign. Sign represents that number of parameters, return type and parameters data type of function is
IG
Programming languages, such as C, C++ and Java use pass by value. It can be simulated passing by
reference with help of dereferenced pointers as arguments in function definition and passing in the
O
address of the operator and on variables while calling the function. It can be passed in as a copy of the
pointer but it points to the same address in memory as the original pointer. It enables the function to
C
change value outside the function. The arguments passed inside the function are termed as dereferenced
pointers. According to the programmer’s perspective, it is the same as working with the values. By using
the same structure in the swap function using pointers, the values outside the function will be swapped.
Sample program:
If we run the above example, the values will be sapped when swap() function has been called.
Void swap (int *firstvar, int *secondvar)
{
4
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY
int temp;
// dereferenced pointers refers to the function is working with values at
addresses which can be passed in
temp=*firstvar;
*firstvar=*secondvar;
*secondvar=temp;
return;
}
int main(void)
{
D
int m = 100;
int n = 200;
E
printf("before swap: value of m: %d \n", m);
V
printf("before swap: value of n: %d \n", n);
// using "address of" operator to pass in the address of each variable
R
swap(&m, &n);
//check values outside the function after swap function.
E
printf("after swap: value of m: %d \n", m);
printf("after swap: value of n: %d \n", n);
S
return 0;
}
1.6.4 Array of Pointers
E
R
Array of pointers is an indexed set of variables where the variables are called pointers. Pointers are
significant tool for developing, utilising and eliminating all forms of data structures. Array of pointers
T
is helpful for reasons which allow to index large sets of variables numerically. Each pointer in one array
points to the integer in another array. It can be printed by dereferencing the pointers. This code displays
H
#include <iostream>
using namespace std;
R
}
return 0;
C
5
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
Pointer to an array is also acknowledged as array pointer. We are using the pointer to access the
constituents of the array. We have a pointer that emphasis to the (0th) component of the array. We can
similarly declare a pointer that can point to entire array rather than just a single component of the
array. Declaration of the pointer to an array. Declaration of pointer to an array:
extern char (*p)[];
char arr[10];
char (*p)[10] = &arr;
D
The given declaration refers to the pointer to an array of four integers. In this case, we use parenthesis
to denote pointer to an array. It is important to encounter pointer name and indirection operator inside
E
brackets. Sample program for pointer to array is given below:
V
#include <iostream>
using namespace std;
R
int main () {
// an array with 5 elements.
E
double balance[5] = {1000.0, 5.0,2.4, 27.0, 56.0};
double *p;
S
p = balance;
cout << "Array values using pointer " << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "*(p + " << i << ") : ";
E
R
cout << *(p + i) << endl;
}
cout << "Array values using balance as address " << endl;
T
return 0;
}
R
*(p + 1): 5
*(p + 2): 2.4
O
*(p + 3): 27
*(p + 4): 56
C
6
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY
From this program, we can see pointer, which denotes 0th element of the array. We declare a pointer that
can point to an array instead of one element of an array. This pointer is used in the multidimensional
arrays. Syntax for a pointer to array of integer 5
data_type (*var_name)[size_of_array];
Example:
int (*ptr)[5];
From the given example, ptr is the pointer which refers to an array of 5 integers. The given subscript has
high precedence than indirection and it is essential to use the pointer name and indirection operation
inside parentheses. Data type of ptr is a pointer to an array of 5 integers.
D
1.7 Dynamic Memory Allocation Functions
E
In programming, we can see some situations where we may have to manage data that is dynamic. At
V
the time of program execution, the number of data items may change. Several programming languages
prefer dynamic memory allocation to assign memory for runtime variables. The allocation heap will be
R
used which selects pointers. Pointers hold the address of a dynamically created array of data blocks or
objects. Many structure languages choose free stores to provide storage locations. The dynamic memory
E
allocation function is as follows:
Malloc() Realloc()
S
zz zz
zz Calloc() zz Free()
E
R
1.7.1 The malloc() Function
The malloc() function allocates a single block of requested memory. It returns null when the memory is
insufficient. It does not initialise the memory during execution time as it has garbage value. Syntax for
T
malloc() is :{ptr=(cast-type*)malloc(byte-size)}.
H
#include <cstdlib>
using namespace std;
int main()
R
{
int *my_pointer;
Y
{
cout << "Lets intilize 5 memory blocks with odd numbers" << endl << endl;
O
my_pointer[i] = (i*2)+1;
}
cout << "Lets see the values" << endl << endl;
for (int i=0; i<5; i++)
{
cout << "Value at position "<<i << " is "<< *(my_pointer+i) << endl;
}
free(my_pointer);
return 0;
7
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
}
}
The running of a Malloc() function is given below:
Lets intilize 5 memory blocks with odd numbers
Lets see the values
Value at position 0 is 1
Value at position 1 is 3
Value at position 2 is 5
D
Value at position 3 is 7
Value at position 4 is 9
E
1.7.2 calloc() Function
V
The calloc() Function allocates multi block of requested memory. It initialise all bytes to zero and also
R
returns null ifmemory is insufficient. Syntax:{ptr=(cast-type*)malloc(byte-size)}.
Let us see the example of calloc() function is given below:
E
#include <cstdlib>
S
#include <iostream>
using namespace std;
int main() {
int *pointer;
E
R
pointer= (int *)calloc(6, sizeof(int));
if (!pointer) {
cout << "Memory Allocation Failed";
T
exit(1);
}
H
free(pointer);
return 0;
O
}
C
8
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY
D
{
int *ptr, *new_ptr;
E
ptr = (int*) malloc(6*sizeof(int));
if(ptr==NULL)
V
{
cout << "Memory Allocation Failed";
R
exit(1);
}
E
for (int i=0; i<6; i++)
{
S
ptr[i] = i;
} E
new_ptr = (int*) realloc(ptr, 0);
R
if(new_ptr==NULL)
{
cout << "Null Pointer";
T
}
else
H
{
cout << "Not a Null Pointer";
IG
}
return 0;
}
R
The free() is allocated by calloc() or malloc() should be released by using free(0 function. It needs to be
O
mentioned or else it consumes memory until the program exit. Syntax for free() function is :
{free(ptr)}.
C
9
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
D
free(pointer1);
cout << *ptr2;
E
return 0;
V
}
The running output of a free() function is given below:
R
Pointer is Null
8
E
1.8 Structures
S
Structure is a user defined data type that allows storing the amount of different data types. In structure, each
E
element is called a member. It can assess the use of templates and classes as it stores different information.
R
The keywords struct is used to define the structure.
Syntax for structures is given as:
T
struct structurename
{
H
Datatype member1;
Datatype member2;
IG
...
Datatype member;
};
R
{ int id;
char name[10];
P
float salary;
};
O
Self-referential structure refers to the structure have members which refer to structure variable of the
same type. It can be used in dynamic data structures, such as linked list and trees. The definition of self-
referential structure is mentioned here,
struct node {
int d;
struct node *k;
};
10
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY
In the given structure, k is a pointer to struct node variable. It is similar to the pointer to structure
and pointer to any other variable. It is a structure definition that has one member that is a pointer to
a structure of its kind. These structures are essential in applications of linked data structures such as
trees and lists. Contrary, the static data structure such as array where several elements that can be
inserted in the array is restricted by size of the array. It can be expanded or contracted. Operations such
as deletion or insertion of nodes in self-referential structures are straight forward alteration of pointers.
1.9 Unions
D
Union can be defined as user defined data type which has a collection of different variables of different
data types in a same memory location. It can be defined as several members but one member has a
E
value at a specific point in time. It is a user defined data type but structures share the same memory
location.
V
For example :
R
Union
{
E
Char y;
int x;
S
} u;
E
The given example is user defined structure that has two members such as ‘x’ of type int and ‘y’ of type
character. If we evaluate the addresses of ‘x’ and ‘y’, we can see that the addresses are distinct. We can
R
conclude that members in structure do not share the same memory location. Like structure, we define
the union in the same way but union keyword is used for defining union data type. Union contains the
data members, i.e., ‘x’ and ‘y’, also evaluate the addresses of both variables and identified that both
T
variables have the same addresses. It states that union members share the same memory location.
H
1.10 Algorithm
IG
Algorithm is defined as a finite sequence of instructions that can be performed in a finite amount of
effort in a given length of time. Algorithm should be simple and easy to understand. To execute by the
R
computer, we need a program that needs to be written in a formal language. Computers are not flexible
compared to the human mind so programs must contain more information than algorithms. Here, we
Y
may ignore the programming details and focus on the design of algorithms than programs.
P
1.10.1 Characteristics of Algorithm
O
Every algorithm has some important characteristics which need to be followed. The characteristics of
algorithm are described in detail given below:
C
zz Input specified: During the computation, the input is data to be transformed to generate the output.
Algorithm must have well defined or 0 inputs. Input precision needs to know what kind of data, what
type of data and how much should be.
zz Output specified: The output is the data obtained from the computation. Algorithm must have well
defined or 1 output. Output precision needs what kind of data, what form the output and how much
the output be.
11
JGI JAIN DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
zz Effectiveness: If the algorithm wants to be effective, it is significant to get output to be feasible with
the available resources. It does not have redundant and unnecessary steps which could make an
algorithm ineffective.
zz Finiteness: The algorithm should stop eventually. Stopping refers to that you get expected output
that has no possible solution. Algorithm should terminate after a finite number of steps is made.
Algorithm should always terminate after a defined number of steps and not be infinite. It is
significant to create a finite algorithm.
zz Definiteness: Algorithm should specify every step and the steps must be involved in the process.
D
Definiteness means mentioning the sequence of operations for making input into output. Algorithm
should be unambiguous. Each step should be spelled out and must have quantitative data.
E
1.10.2 Elements of Algorithm
V
Algorithms are a sequence of instructions, implemented using programming languages, such as java,
R
C, C++ and so on. The elements of the algorithm are as follows:
zz Selection: It is the use of conditional statements such as if then and if then else
E
zz Sequence: It is the order in which commands and behaviours are integrated into projects to generate
expected outcomes.
S
zz Iteration: Algorithms prefer repetition to execute the steps to a particular number of times or when
E
a particular condition is attained. It is called looping. It changes the project flow by repeating the
behavior until a condition is met.
R
Conclusion 1.11 Conclusion
T
zz A data structure is a defined format for managing, assessing, retrieving and storing data. Data
H
Structures make it easy for users to work with the data they require in different ways.
zz The needs of data structures contain the following: efficiency, re-usability, and invisibility.
IG
zz In the classification of data structure, Trees also originate in the non-primitive and non-linear group
of data structure.
R
zz Data Structure is well-defined as a mathematical or logical model to store data and perform
operation on the stored data.
Y
zz A Pointer is a derived data type that stores the address of another variable.
P
1.12 Glossary
O
12
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY
D
c. Arrangement of data
d. All of these
E
2. __________ are the basic data structures that can be operated on machine and data instructions
V
directly.
a. Primitive data structures
R
b. Non-primitive data structures
E
c. Linear data structures
S
d. None of these
3. Which of the following data structure is a nonlinear type?
E
a. Lists
R
b. Strings
c. Stacks
T
d. None of these
H
b. Queues
c. Strings
R
d. All of these
Y
5. Which is true from the following for prior using a pointer variable?
a. It should be declared
P
b. It should be initialised
O
d. None of these
6. Comment on following declaration Int *ptr l;
a. Ptr and l are pointers to integer
b. Ptr is a pointer to integer, l is not
c. Ptr and p are not pointers to integers
d. Ptr is a pointer to integer, l may or may not be
13
JGI JAIN
DEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
7. When the user attempts to remove the element from the empty stack then the condition is said to be
a _______
a. Underflow
b. collection of garbage
c. overflow
d. None of these
8. Which data structure is generally used for executing the recursive algorithm?
D
a. Queue
E
b. Stack
c. Heap sort
V
d. Linked list
R
9. Which among the following is the method of inserting an element in the stack?
a. Insert
E
b. Add
S
c. Push
d. None of these
E
R
10. What is alternative name for the circular queue from the following options?
a. Cone buffer
T
b. Square buffer
c. Ring buffer
H
d. None of these
IG
structure has information related to the data values. What is a Data structure?
2. Data structure offers a means of establishing, handling, and storage data efficiently. It also comprises
Y
3. Trees also originate in the non-primitive and non-linear group of data structure, using tree we can
signify a hierarchical relationship between the data components. Describe the classification of data
O
structure.
4. In programming, we can see some situations where we may have to manage data that is dynamic.
C
At the time of program execution, the number of data items may change. Describe the significance
of dynamic memory allocation functions.
5. To execute by the computer, we need a program that needs to be written in a formal language.
Determine the importance of algorithm.
14
UNIT 01: Introduction to Data Structures JGI JAIN
DEEMED-TO-BE UNIVERSITY
Q. No. Answer
D
2. a. Primitive data structures
E
4. d. All of these
V
5. c. It should be both declared or initialised
R
6. a. Ptr and l are pointers to integer
E
7. a. Underflow
8. b. Stack
S
9. c. Push
effectively later. It can be arranged in various ways, such as the mathematical or logical model for
H
the specific organisation of data is known as data structure. Refer to Section Data structures
2. The needs of data structures contain the following: efficiency, re-usability, and invisibility. Data
IG
structure offers a means of establishing, handling, and storage data efficiently. It also comprises
the collection of data as well as the actions that can be applied to that data. Refer to Section Need of
Data structures
R
3. In the classification of data structure, Trees also originate in the non-primitive and non-linear
group of data structure, using tree we can signify a hierarchical relationship between the data
Y
4. Dynamic memory allocation is used assign memory for runtime variables. The allocation heap will
be used which selects pointers. Pointers hold the address of a dynamically created array of data
O
blocks or objects. Many structure languages choose free stores to provide storage locations. Refer to
Section Dynamic Memory Allocation Functions
C
5. Algorithm is defined as a finite sequence of instructions that can be performed in a finite amount
of effort in a given length of time. Algorithm should be simple and easy to understand. To execute
by the computer, we need a program that needs to be written in a formal language. Refer to Section
Algorithm
15
JGI JAINDEEMED-TO-BE UNIVERSITY
Data Structures with Algorithms
zz https://www.iare.ac.in/sites/default/files/PPT/IARE_DS_PPT_3.pdf
zz https://www.iare.ac.in/sites/default/files/DS.pdf
D
zz You can discuss with your friends the applications of data structures in a real-life environment,
Classification of data structure and its need . Also discussed on pointers and Algorithm of data
E
structure.
V
R
E
S
E
R
T
H
IG
R
Y
P
O
C
16