0% found this document useful (0 votes)
27 views

MCA Data Structures With Algorithms 01

Uploaded by

SAI SRIRAM
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

MCA Data Structures With Algorithms 01

Uploaded by

SAI SRIRAM
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

UNIT

01 Introduction to Data Structures

Names of Sub-Units

Introduction to Data Structure: Classi�ication of Data Structures, Data Structure Operations, Basic
Concepts of Pointers, Structures and Union, Algorithm, Characteristics of the Algorithm.

Overview

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
representing stack. Towards the end, the unit discusses the application of stack.

Learning Objectives

In this unit, you will learn to:


 Discuss the concept of data structures
 Explain the concept of classi�ication of data structures
 Describe the operations of data structure
 Explain the signi�icance of basic concepts of pointers, structures and union
 Discuss the characteristics of the algorithm
Data Structures with Algorithms

Learning Outcomes

At the end of this unit, you would:


 Evaluate the concept of Data Structure
 Assess the concept of classi�ication of data structure
 Evaluate the importance of operations of data structure
 Determine the signi�icance of Algorithm
 Explore the characteristics of algorithm

Pre-Unit Preparatory Material

 https://www.studytonight.com/data-structures/introduction-to-data-structures
 https://www.geeksforgeeks.org/data-structures/

1.1 INTRODUCTION
A data structure is a de�ined format for managing, assessing, retrieving and storing data. Data
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
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.

1.2 DATA STRUCTURES


Data structure is a way to store and organise data in computer memory so that data can be used
effectively later. It can be arranged in various ways, such as the mathematical or logical model for
the speci�ic 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 de�ined 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
required. Data structure is the process of arranging data and its functions.

1.3 NEED OF DATA STRUCTURE


The needs of data structures contain the following: ef�iciency, re-usability, and invisibility. Data structure
offers a means of establishing, handling, and storage data ef�iciently. It also comprises the collection of
data as well as the actions that can be applied to that data.
Data structures are signi�icant for the following reasons:
 Data structure helps the programmers in effectively managing the data. It serves a greater role in
improving the performance of software or program.
 Data structures are used in every program or software system to arrange the data ef�iciently.
 Data structures enable data to be stored in a particular manner in the memory.
 Data structure is a signi�icant factor for different ef�icient algorithms. It enables to manage a large
amount of data, such as a large collection of databases and indexing services, such as hash table.

2
UNIT 01: Introduction to Data Structures

 Data structure helps in data retrieval and search effectively.


 Data structures manage the retrieval and storage of data and information which can be stored in
secondary and main memory.

1.4 CLASSIFICATIONS OF DATA STRUCTURE


In the classi�ication 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 components.
The CREATE operation (it can be de�inite) results in storing memory for the program components. Data
structure is classi�ied into the primitive and non-primitive data structures are as follows:
 Primitive data structures: Primitive data structures are the basic data structures that can
be operated on machine and data instructions directly. It can be de�ined by the programming
languages. Primitive data types are integer, �loating point number, real and pointer.
 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
linked lists

1.5 DATA STRUCTURE OPERATIONS


Data Structure is well-de�ined 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
structure has some common operations to manipulate data and process it for the user. The operation
on data structures are as follows:
 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.
For example: if we want to compute the average of marks secured by students in �ive different
subjects. We need to traverse the array of marks and compute the total sum. We will divide that sum
by several subjects, i.e, 5, to compute the average.
 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.
 Deletion: The phenomenon of removing the element from the data structure is known as deletion.
We delete the element from the data structure at any location. Under�low condition occurs when
trying to delete an element from the empty data structure.
 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.
 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
and bubble sort.
 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
Data Structures with Algorithms

Further description about the Pointer is discussed below:

1.6.1 Pointer Basics


Pointers are the variables that can be used to store the location of value found in the memory. It refers to
the location that holds its memory address. The phenomenon of acquiring value stored at the location
is a reference by the pointer is called dereferencing. It is the same as an index for textbooks where each
page can be referred by the page number found in index. By using this concept, one can able to identify
the page using the location referred to a particular index. These pointers are used in the dynamic
implementation of different data structures, such as lists or stacks. An example of pointer basics that
is declaring pointers is given below:
 Declaring pointers: Pointer declarations is * operation. The syntax is,
int a=12;
int *ptr; //pointer declaration
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
of integer variable.

1.6.2 Pointer with functions


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
pointers, it is signi�icant 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
evaluated at run time is known as late binding.
Syntax:
Returntype (*function pointer) (parameter1, parameter2);
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
the same. For example:
int (*pfunc) (int l, int M);
// pfunc generally takes integers as return values and parameters.
int plus (int l, int K)
//in this function, the address is valued by the function pointer.
1.6.3 Pass by Reference
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 de�inition and passing in the
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
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

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)
{
int m = 100;
int n = 200;
printf("before swap: value of m: %d \n", m);
printf("before swap: value of n: %d \n", n);
// using "address of" operator to pass in the address of each variable
swap(&m, &n);
//check values outside the function after swap function.
printf("after swap: value of m: %d \n", m);
printf("after swap: value of n: %d \n", n);
return 0;
}

1.6.4 Array of Pointers


Array of pointers is an indexed set of variables where the variables are called pointers. Pointers are
signi�icant tool for developing, utilising and eliminating all forms of data structures. Array of pointers
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
the value in memory of where pointers refer.
An sample program for array of pointers is as follows:
#include <iostream>
using namespace std;
const int MAX = 4;
int main () {
int var[MAX] = {20, 200, 400 ,600};
for (int i = 0; i < MAX; i++) {
cout << "Value of var[" << i << "] = ";
cout << var[i] << endl;
}
return 0;
}

The running output of an pointer of array is as follows:


Value of var[0] = 20
Value of var[1] = 200
Value of var[2] = 400
Value of var[3] = 600

5
Data Structures with Algorithms

1.6.5 Pointer to Array

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;
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
brackets. Sample program for pointer to array is given below:
#include <iostream>
using namespace std;
int main () {
// an array with 5 elements.
double balance[5] = {1000.0, 5.0,2.4, 27.0, 56.0};
double *p;
p = balance;
cout << "Array values using pointer " << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
cout << "Array values using balance as address " << endl;
for ( int i = 0; i < 5; i++ ) {
cout << "*(balance + " << i << ") : ";
cout << *(balance + i) << endl;
}
return 0;
}

The running output of a pointer to array with 5 elements is as follows:


Array values using pointer
*(p + 0): 1000
*(p + 1): 5
*(p + 2): 2.4
*(p + 3): 27
*(p + 4): 56
Array values using balance as address
*(balance + 0): 1000
*(balance + 1): 5
*(balance + 2): 2.4
*(balance + 3): 27
*(balance + 4): 56

6
UNIT 01: Introduction to Data Structures

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.

1.7 DYNAMIC MEMORY ALLOCATION FUNCTIONS


In programming, we can see some situations where we may have to manage data that is dynamic. At
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
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
allocation function is as follows:
 Malloc()  Realloc()
 Calloc()  Free()

1.7.1 The malloc() Function


The malloc() function allocates a single block of requested memory. It returns null when the memory is
insuf�icient. It does not initialise the memory during execution time as it has garbage value. Syntax for
malloc() is :{ptr=(cast-type*)malloc(byte-size)}.
Let us see the example of malloc() function is given below:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int *my_pointer;
my_pointer = (int*) malloc(5*sizeof(int));
if(my_pointer)
{
cout << "Lets intilize 5 memory blocks with odd numbers" << endl << endl;
for (int i=0; i<5; i++)
{
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
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
Value at position 3 is 7
Value at position 4 is 9

1.7.2 calloc() Function


The calloc() Function allocates multi block of requested memory. It initialise all bytes to zero and also
returns null ifmemory is insuf�icient. Syntax:{ptr=(cast-type*)malloc(byte-size)}.
Let us see the example of calloc() function is given below:
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
int *pointer;
pointer= (int *)calloc(6, sizeof(int));
if (!pointer) {
cout << "Memory Allocation Failed";
exit(1);
}
cout << "Initializing values..." << endl
<< endl;
for (int i = 0; i < 6; i++) {
pointer[i] = i * 2 + 1;
}
cout << "Initialized values" << endl;
for (int i = 0; i < 6; i++) {
/* ptr[i] and *(ptr+i) can be used interchangeably */
cout << *(pointer + i) << endl;
}
free(pointer);
return 0;
}
The running output of a Calloc() is given below:
Initialized values
1
3
5
7
9
11

8
UNIT 01: Introduction to Data Structures

1.7.3 realloc() Function


When the memory is insuf�icient for calloc() or malloc(), we can reallocate the memory using realloc(). It
rearranges or changes the memory size.
Let's us see an example of realloc() function is as follows:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int *ptr, *new_ptr;
ptr = (int*) malloc(6*sizeof(int));
if(ptr==NULL)
{
cout << "Memory Allocation Failed";
exit(1);
}
for (int i=0; i<6; i++)
{
ptr[i] = i;
}
new_ptr = (int*) realloc(ptr, 0);
if(new_ptr==NULL)
{
cout << "Null Pointer";
}
else
{
cout << "Not a Null Pointer";
}
return 0;
}
The output of a realloc() function is given below:
Null Pointer

1.7.4 free() Function


The free() is allocated by calloc() or malloc() should be released by using free(0 function. It needs to be
mentioned or else it consumes memory until the program exit. Syntax for free() function is :
{free(ptr)}.
Let's see an example of free() function is given below:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int x = 8;

9
Data Structures with Algorithms

int *pointer1 = NULL;


int *ptr2 = &x;
if(pointer1)
{
cout << "Pointer is not Null" << endl;
}
else
{
cout << "Pointer is Null" << endl;
}
free(pointer1);
cout << *ptr2;
return 0;
}
The running output of a free() function is given below:
Pointer is Null
8

1.8 STRUCTURES
Structure is a user de�ined data type that allows storing the amount of different data types. In structure, each
element is called a member. It can assess the use of templates and classes as it stores different information.
The keywords struct is used to de�ine the structure.
Syntax for structures is given as:
struct structurename
{
Datatype member1;
Datatype member2;
...
Datatype member;
};
Example of a structure is as follows:
struct employee
{ int id;
char name[10];
float salary;
};

1.8.1 Self-referential Structures


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 de�inition of self-
referential structure is mentioned here,
struct node {
int d;
struct node *k;
};

10
UNIT 01: Introduction to Data Structures

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 de�inition 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

Union can be de�ined as user de�ined data type which has a collection of different variables of different
data types in a same memory location. It can be de�ined as several members but one member has a
value at a speci�ic point in time. It is a user de�ined data type but structures share the same memory
location.
For example :
Union
{
Char y;
int x;
} u;
The given example is user de�ined 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
conclude that members in structure do not share the same memory location. Like structure, we de�ine
the union in the same way but union keyword is used for de�ining union data type. Union contains the
data members, i.e., ‘x’ and ‘y’, also evaluate the addresses of both variables and identi�ied that both
variables have the same addresses. It states that union members share the same memory location.

1.10 ALGORITHM

Algorithm is de�ined as a �inite sequence of instructions that can be performed in a �inite 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. Computers are not �lexible
compared to the human mind so programs must contain more information than algorithms. Here, we
may ignore the programming details and focus on the design of algorithms than programs.

1.10.1 Characteristics of Algorithm


Every algorithm has some important characteristics which need to be followed. The characteristics of
algorithm are described in detail given below:
 Input speci�ied: During the computation, the input is data to be transformed to generate the output.
Algorithm must have well de�ined or 0 inputs. Input precision needs to know what kind of data, what
type of data and how much should be.
 Output speci�ied: The output is the data obtained from the computation. Algorithm must have well
de�ined or 1 output. Output precision needs what kind of data, what form the output and how much
the output be.

11
Data Structures with Algorithms

 Effectiveness: If the algorithm wants to be effective, it is signi�icant to get output to be feasible with
the available resources. It does not have redundant and unnecessary steps which could make an
algorithm ineffective.
 Finiteness: The algorithm should stop eventually. Stopping refers to that you get expected output
that has no possible solution. Algorithm should terminate after a �inite number of steps is made.
Algorithm should always terminate after a de�ined number of steps and not be in�inite. It is
signi�icant to create a �inite algorithm.
 De�initeness: Algorithm should specify every step and the steps must be involved in the process.
De�initeness 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.

1.10.2 Elements of Algorithm


Algorithms are a sequence of instructions, implemented using programming languages, such as java,
C, C++ and so on. The elements of the algorithm are as follows:
 Selection: It is the use of conditional statements such as if then and if then else
 Sequence: It is the order in which commands and behaviours are integrated into projects to generate
expected outcomes.
 Iteration: Algorithms prefer repetition to execute the steps to a particular number of times or when
a particular condition is attained. It is called looping. It changes the project �low by repeating the
behavior until a condition is met.

Conclusion 1.11 CONCLUSION

 A data structure is a de�ined format for managing, assessing, retrieving and storing data. Data
Structures make it easy for users to work with the data they require in different ways.
 The needs of data structures contain the following: ef�iciency, re-usability, and invisibility.
 In the classi�ication of data structure, Trees also originate in the non-primitive and non-linear group
of data structure.
 Data Structure is well-de�ined as a mathematical or logical model to store data and perform
operation on the stored data.
 A Pointer is a derived data type that stores the address of another variable.

1.12 GLOSSARY

 Algorithm: a technique used to solve the problem


 Allocation: allocating memory for an object in the memory
 Data: contains information
 Pointer: variable who value is the address of another variable
 Dynamic memory allocation: programming technique where linked objects in data structures are
developed from free store. If no longer is needed, then the object is left as garbage or returned to a free
store.

12
UNIT 01: Introduction to Data Structures

1.13 SELF-ASSESSMENT QUESTIONS

A. Essay Type Questions


1. The basic algorithm operations are integrated into the design of the data structure. Each data
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 ef�iciently. It also comprises
the collection of data as well. Explain the need of data structures.
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 classi�ication of data
structure.
4. In programming, we can see some situations where we may have to manage data that is dynamic.
At the time of program execution, the number of data items may change. Describe the signi�icance
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.

1.14 ANSWERS AND HINTS FOR SELF-ASSESSMENT QUESTIONS

A. Hints for Essay Type Questions


1. Data structure is a way to store and organise data in computer memory so that data can be used
effectively later. It can be arranged in various ways, such as the mathematical or logical model for
the speci�ic organisation of data is known as data structure. Refer to Section Data structures
2. The needs of data structures contain the following: ef�iciency, re-usability, and invisibility. Data
structure offers a means of establishing, handling, and storage data ef�iciently. 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
3. In the classi�ication 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
components. Refer to Section Classi�ication of Data Structure
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
blocks or objects. Many structure languages choose free stores to provide storage locations. Refer to
Section Dynamic Memory Allocation Functions
5. Algorithm is de�ined as a �inite sequence of instructions that can be performed in a �inite 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

13
Data Structures with Algorithms

@ 1.15 POST-UNIT READING MATERIAL

 https://www.iare.ac.in/sites/default/�iles/PPT/IARE_DS_PPT_3.pdf
 https://www.iare.ac.in/sites/default/�iles/DS.pdf

1.16 TOPICS FOR DISCUSSION FORUMS

 You can discuss with your friends the applications of data structures in a real-life environment,
Classi�ication of data structure and its need . Also discussed on pointers and Algorithm of data
structure.

14

You might also like