SlideShare a Scribd company logo
1 of 42
COMPUTER SCIENCE II
[DATA STRUCTURES]
UNIT – I
INTRODUCTION
PART I
DATA STRUCTURES
• Organizing or structuring data while storing in a computer
• Mathematical or logical model (we will construct these models in C language)of a particular
organization of data items.
•Ex. Can store a list of items having the same data-type using the array data structure
Data Structure mainly specifies the following
four things:
· Organization of Data ( amount of memory required to store)
· Accessing methods (amount of time required to process)
· Degree of associativity (how the data items are related to each other)
· Processing alternatives for information (only then can we know the best)
Basic Terminology
Data: Data can be defined as an elementary value or the collection of values, for example, student's
name and its id are the data about the student.
Group Items: Data items which have subordinate data items are called Group item, for example,
name of a student can have first name and the last name.
Record: Record can be defined as the collection of various data items, for example, if we talk about
the student entity, then its name, address, course and marks can be grouped together to form the
record for the student.
File: A File is a collection of various records of one type of entity, for example, if there are 60 student
in the class, then there will be 20 records in the related file where each record contains the data
about each student.
Attribute and Entity: An entity represents the class of certain objects. it contains various attributes.
Each attribute represents the particular property of that entity.
Field: Field is a single elementary unit of information representing the attribute of an entity.
Need of Data Structures
Processor speed: To handle very large amount 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.
Advantage and Disadvantage
Classification of Data Structure
· Primitive data structures
· Non-primitive data structures (linear and non-linear)
· Homogeneous and non-homogeneous data structures
· Static and dynamic data structures
1. Primitive data structures :
 Basic data structures and are directly operated upon by the machine instructions.
 Classified into - integers, floating point numbers, characters, string constants, pointers etc.
Like: int a =10;
The corresponding machine level code will be like:
store the int value in so and so location.
But if I write: int arr[10]=20;
The machine instruction doesn’t know array index 10! So, intermediate steps will be there to
convert this particular instruction to machine level.
2. Non-primitive data structures:
It is advanced data structure emphasizing on structuring of a group of data items.
They cannot be directly operated upon by the machine instructions.
Example: Array, list, files, linked list, trees and graphs fall in this category.
Linear and non-linear data structures :
In a linear data structure, the data items are arranged in a linear sequence.
For example: array.
In a non-linear data structure, the data items are not in sequence.
For Example: trees and graphs.
Cont’
Linear and non-linear data structures :
In a linear data structure, the data items are arranged in a linear sequence.
For example: array.
In a non-linear data structure, the data items are not in sequence.
For Example: trees and graphs.
3. Homogeneous and non-
homogeneous data structures:
In homogeneous data structure, all the elements are of same type.
For Example: arrays.
In non-homogeneous data structure, the elements may or may not be of the same type.
For Example: Records.
4. Static and dynamic data structures:
In Static data structure the size of the structure is fixed.
The content of the data structure can be modified but without changing the memory space
allocated to it.
Example: Array
In Dynamic data structure the size of the structure is not fixed and can be modified during the
operations performed on it.
 Dynamic data structures are designed to facilitate change of data structures in the run time.
Example: Linked List
Operations on Data Structures
1) Create:- The create operation results in reserving memory for program elements. This can be done by declaration statement.
Creation of data structure may take place either during compile-time or run-time.
 Dynamic Memory Allocation in C can be done using malloc(), calloc(), free() and realloc()
2) Destroy:- Destroy operation destroys memory space allocated for specified data structure. free() function of C language is used to
destroy data structure.
3) Selection:- Selection operation deals with accessing a particular data within a data structure.
4) Updation:- It updates or modifies the data in the data structure.
5) Searching:- It finds the presence of desired data item in the list of data items, it may also find the locations of all elements that satisfy
certain conditions.
6) Sorting:- Sorting is a process of arranging all data items in a data structure in a particular order, say for example, either in ascending
order or in descending order.
7) Merging:- Merging is a process of combining the data items of two different non-primitive data structure into a single one.
8) Splitting:- Splitting is a process of partitioning single non-primitive data structure to multiple ones.
9) Traversal:- Traversal is a process of visiting each and every node of a non-primitive data structure in systematic manner.
UNIT – I
Dynamic Memory Allocation
Part II
Memory allocation
Static memory allocation
In Static Memory Allocation the memory for
your data is allocated when the program starts.
The size is fixed when the program is created.
This memory allocation is fixed and cannot be
changed, i.e. increased or decreased after
allocation. So, exact memory requirements
must be known in advance.
Key features:
· Variables get allocated permanently
· Allocation is done before program
execution
· It uses the data structure called stack for
implementing static allocation
· There is no memory reusability
Example:
All the variables in the program below are statically
allocated.
void play
{
int a;
}
int main()
{
int b;
int c[10];
return 1;
}
Static memory allocation
the address can be obtained by using ‘&’ operator and can be assigned to a pointer.
The memory is allocated during compile time.
It uses stack for maintaining the static allocation of memory.
In this allocation, once the memory is allocated, the memory size cannot change.
It is less efficient.
Dynamic memory allocation
 C is a structured language, it has some fixed rules for programming. One of it includes
changing the size of an array. An array is collection of items stored at continuous memory
locations.
Procedure refer as dynamic allocation
a procedure in which the size of a data structure is changed during the runtime.
Dynamic allocation is useful when data structures need to be created whose size is not known until run
time
Dynamic memory
Allocating memory dynamically. While programming, if you are aware of the size of an array,
then it is easy and you can define it as an array.
Example Code
Output. ...
Resizing Memory Locations
Library functions
C provides some functions to achieve these tasks. There are 4 library functions provided by C
defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming.
They are:
1. malloc()
2. calloc()
3. free()
4. realloc()
malloc():
“malloc” or “memory allocation” method in C is used to dynamically allocate a single large block
of memory with the specified size. It returns a pointer of type void which can be cast into a
pointer of any form.
Syntax:
ptr = (cast-type*) malloc(byte-size)
For Example:
ptr = (int*) malloc(100 * sizeof(int));
Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the
pointer ptr holds the address of the first byte in the allocated memory.
calloc
“calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified
number of blocks of memory of the specified type. It also returns a pointer of type void which
can be cast into a pointer of any form. It initializes each block with a default value ‘0’.
Syntax:
ptr = (cast-type*)calloc(n, element-size);
For Example:
ptr = (float*) calloc(25, sizeof(float));
This statement allocates contiguous space in memory for 25 elements each with the size of the
float.
realloc()
“realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of
a previously allocated memory.
In other words, if the memory previously allocated with the help of malloc or calloc is
insufficient, realloc can be used to dynamically re-allocate memory.
Syntax:
ptr = realloc(ptr, newSize);
where ptr is reallocated with new size 'newSize'
Free
“free” method in C is used to dynamically de-allocate the memory.
The memory allocated using functions malloc() and calloc() is not de-allocated on their own.
Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps
to reduce wastage of memory by freeing it.
Syntax:
free(ptr);
UNIT – I
Recursion
Part III
Recursion
Recursion is the process of repeating items in a self-similar way.
In programming languages, if a program allows you to call a function inside the same function,
then it is called a recursive call of the function.
Use - to solve many mathematical problems, such as calculating the factorial of a number,
generating Fibonacci series, etc.
void recursion()
{
recursion(); /* function calls itself */
}
int main()
{
recursion();
}
Types
Recursion are mainly of two types depending on whether a function calls itself from within
itself or more than one function call one another mutually.
Types:
Direct recursion
Indirect recursion
Direct Recursion:
◦ Tail Recursion
◦ If a recursive function calling itself and that recursive call is the last statement in the function
◦ Head Recursion
◦ If a recursive function calling itself and that recursive call is the first statement in the function
◦ Tree Recursion
◦ First understand linear recursion. If a recursive function calling itself for one time then it’s known as Linear Recursion
◦ Otherwise if a recursive function calling itself for more than one time – tree recursion
◦ Nested Recursion
◦ a recursive function will pass the parameter as a recursive call -“recursion inside recursion
Cont’
Indirect recursion
there may be more than one function and they are calling one another in a circular manner.
Example
Binomial coefficient
Fibanacci series
GCD
Tower of Hanoi
Binomial coefficient
Algorithm
Step1: Start
Step2: Accept two numbers n and r
Step3: If n<r
Print “Invalid input”
Else
Print result
End if
Step4: Stop
Algorithm for BC(x)
Step1: If x=0
return 1
Else
return BC(n-1,r-1) + BC(n-1,r)
End if
Binomial Coefficient
//Program to find Binomial Coefficient
#include<stdio.h>
int main()
{
int n,r;
printf("Enter n value : ");
scanf("%d",&n);
printf("Enter r value : ");
scanf("%d",&r);
if(n<r)
{
printf("n Invalid input n value must be greater than r value");
}
else
{
printf("Binomial coefficientn",BC(n,r));
printf("%dn",BC(n,r));
return 0;
}
}
int BC(int n, int r)
{
if(r==0 || r==n)
return 1;
return BC(n-1,r-1) + BC(n-1,r);
}
Output:
Enter n value : 3
Enter r value :6
Invalid input n value must be greater than r value
Enter n value : 4
Enter r value :2
Binomial coefficient
6
GCD
Program to find GCD of two numbers using recursion
Algorithm
Step1: Start
Step2: Accept two numbers m and n
Step3: Call the function gcd(m,n)
Step4: Print the result
Step5: Stop
Algorithm for gcd(a,b)
Step1: If a==b
return (a)
else
if(a>b)
return(gcd(a-b,b)
else
return (gcd(a,b-a)
End if
#include<stdio.h>
int gcd(int,int);
void main()
{
int m,n;
printf("nGreatest Common Divisorn");
printf("Enter the value for m : ");
scanf("%d",&m);
printf("Enter the value for n : ");
scanf("%d",&n);
printf("The Greatest Common Divisor of %d and %d = %d",m,n,gcd(m,n));
}
int gcd(int a,int b)
{
if(a==b)
{
return(a);
}
else
{
if(a>b)
return(gcd(a-b,b));
else
return(gcd(a,b-a));
}
Fibanacci series
#include<stdio.h>
#include<conio.h>
int recursivefibonacci(int);
int main(){
int m, x;
printf("Please enter the total number of values you want in the
Fibonacci series : n");
scanf("%d",&m);
printf("The Fibonacci series of these numbers would be equal to : n");
for(x=0;x<m;x++) {
printf("%d",recursivefibonacci(x));
}
getch();
}
int recursivefibonacci(int x){
if(x==0) return 0;
else if(x==1) return 1;
else return (recursivefibonacci(x-1) + recursivefibonacci(x-
2));
}
Please enter the total number of values you want in the
Fibonacci series :
4
The Fibonacci series of these numbers would be equal to :
0112
Output:
Please enter the total number of values
you want in the Fibonacci series :
4
The Fibonacci series of these numbers
would be equal to :
0112
Tower of hanoi
Tower of Hanoi, is a mathematical puzzle which
consists of three towers (pegs) and more than one
rings is as depicted − These rings are of different
sizes and stacked upon in an ascending order, i.e. the
smaller one sits over the larger one.
The objective of the puzzle is to move the entire
stack to the last rod, obeying the following rules:
Only one disk may be moved at a time.
Each move consists of taking the upper disk from one
of the stacks and placing it on top of another stack or
on an empty rod.
No disk may be placed on top of a disk that is smaller
than it.
With 3 disks, the puzzle can be solved in 7 moves.
The minimal number of moves required to solve a
Tower of Hanoi puzzle is 2n − 1, where n is the
number of disks.
Exercise 1
Exercise 2
#include<stdio.h>
void TOH(int n,char x,char y,char z)
{
if(n>0)
{
TOH(n-1,x,z,y);
printf("n%c to %c",x,y);
TOH(n-1,z,y,x);
}
}
int main()
{
int n;
scanf("%d",&n);
TOH(n,'A','B','C');
}
Program
#include<stdio.h>
#include<math.h>
void main()
{
int n;
char A,B,C;
void towers(int,char,char,char);
// clrscr();
printf("nTowers of Hanoin");
printf("nEnter the number of disks : ");
scanf("%d",&n);
printf("The number of
moves=%0.fn",(pow(2,n)-1));
printf("nTowers of Hanoi simulation for %d
disksn",n);
towers(n,'A','C','B');
getch();
}
void towers(int n,char source,char dest,char aux)
{
if(n==1)
{
printf("nMove disk %d from %c to
%c",n,source,dest);
return;
}
towers(n-1,source,aux,dest);
printf("nMove disk %d from %c to
%c",n,source,dest);
towers(n-1,aux,dest,source);
}
output
Towers of Hanoi
Enter the number of disks : 3
The number of moves=7
Towers of Hanoi simulation for 3 disks
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
Algorithm
Step1: Start
Step2: Input the number of disks
Step3: Print the number of movements 2disk-1
Step4: Call the function towers(n,’A’,’C’,’B’)
Step5:Stop
Algorithm for towers(n,source,dest,aux)
n is the total no. of disks and A, B, and C are the source, destination and intermediate pegs respectively.
Step1: If n=1
Print the movement source to destination
Else
Step a: Call the function towers(n-1,source,aux,dest)
Step b: Print the movement source to destination
Step c: Call the function towers(n-1,aux,dest,source)
End if
THANK YOU..
thenmithu@gmail.com

More Related Content

Similar to Data Structures_Introduction

Introduction to DS.pptx
Introduction to DS.pptxIntroduction to DS.pptx
Introduction to DS.pptx
OnkarModhave
 

Similar to Data Structures_Introduction (20)

Introduction to data structure
Introduction to data structureIntroduction to data structure
Introduction to data structure
 
DataStructurePpt.pptx
DataStructurePpt.pptxDataStructurePpt.pptx
DataStructurePpt.pptx
 
UNIT II.docx
UNIT II.docxUNIT II.docx
UNIT II.docx
 
Unit 1-Introduction to Data Structures-BCA.pdf
Unit 1-Introduction to Data Structures-BCA.pdfUnit 1-Introduction to Data Structures-BCA.pdf
Unit 1-Introduction to Data Structures-BCA.pdf
 
Datastructures Notes
Datastructures NotesDatastructures Notes
Datastructures Notes
 
Introduction to data structures (ss)
Introduction to data structures (ss)Introduction to data structures (ss)
Introduction to data structures (ss)
 
Data Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptxData Structure & aaplications_Module-1.pptx
Data Structure & aaplications_Module-1.pptx
 
Introduction to Data Structure
Introduction to Data StructureIntroduction to Data Structure
Introduction to Data Structure
 
Data Structure & Algorithm.pptx
Data Structure & Algorithm.pptxData Structure & Algorithm.pptx
Data Structure & Algorithm.pptx
 
UNIT I - Data Structures.pdf
UNIT I - Data Structures.pdfUNIT I - Data Structures.pdf
UNIT I - Data Structures.pdf
 
Introduction to DS.pptx
Introduction to DS.pptxIntroduction to DS.pptx
Introduction to DS.pptx
 
Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)Chapter 1( intro &amp; overview)
Chapter 1( intro &amp; overview)
 
Lecture 2 Data Structure Introduction
Lecture 2 Data Structure IntroductionLecture 2 Data Structure Introduction
Lecture 2 Data Structure Introduction
 
Chapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdfChapter 1 Introduction to Data Structures and Algorithms.pdf
Chapter 1 Introduction to Data Structures and Algorithms.pdf
 
b,Sc it data structure.pptx
b,Sc it data structure.pptxb,Sc it data structure.pptx
b,Sc it data structure.pptx
 
DataStructurePpt.pptx
DataStructurePpt.pptxDataStructurePpt.pptx
DataStructurePpt.pptx
 
Lect 1-2 Zaheer Abbas
Lect 1-2 Zaheer AbbasLect 1-2 Zaheer Abbas
Lect 1-2 Zaheer Abbas
 
MD AZAM CA-1-1.pptx
MD AZAM CA-1-1.pptxMD AZAM CA-1-1.pptx
MD AZAM CA-1-1.pptx
 
b,Sc it data structure.pptx
b,Sc it data structure.pptxb,Sc it data structure.pptx
b,Sc it data structure.pptx
 
Unit-1 DataStructure Intro.pptx
Unit-1 DataStructure Intro.pptxUnit-1 DataStructure Intro.pptx
Unit-1 DataStructure Intro.pptx
 

More from ThenmozhiK5 (8)

Software Engineering _ Introduction
Software Engineering _ IntroductionSoftware Engineering _ Introduction
Software Engineering _ Introduction
 
Artificial Intelligence_ Knowledge Representation
Artificial Intelligence_ Knowledge RepresentationArtificial Intelligence_ Knowledge Representation
Artificial Intelligence_ Knowledge Representation
 
Artificial Intelligence_Introduction
Artificial Intelligence_IntroductionArtificial Intelligence_Introduction
Artificial Intelligence_Introduction
 
Artificial Intelligence_NLP
Artificial Intelligence_NLPArtificial Intelligence_NLP
Artificial Intelligence_NLP
 
Artificial Intelligence_Outline
Artificial Intelligence_OutlineArtificial Intelligence_Outline
Artificial Intelligence_Outline
 
Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & Searching
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked List
 
DS - OUTLINE.pptx
DS - OUTLINE.pptxDS - OUTLINE.pptx
DS - OUTLINE.pptx
 

Recently uploaded

Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
MateoGardella
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Recently uploaded (20)

APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

Data Structures_Introduction

  • 1. COMPUTER SCIENCE II [DATA STRUCTURES] UNIT – I INTRODUCTION PART I
  • 2. DATA STRUCTURES • Organizing or structuring data while storing in a computer • Mathematical or logical model (we will construct these models in C language)of a particular organization of data items. •Ex. Can store a list of items having the same data-type using the array data structure
  • 3. Data Structure mainly specifies the following four things: · Organization of Data ( amount of memory required to store) · Accessing methods (amount of time required to process) · Degree of associativity (how the data items are related to each other) · Processing alternatives for information (only then can we know the best)
  • 4. Basic Terminology Data: Data can be defined as an elementary value or the collection of values, for example, student's name and its id are the data about the student. Group Items: Data items which have subordinate data items are called Group item, for example, name of a student can have first name and the last name. Record: Record can be defined as the collection of various data items, for example, if we talk about the student entity, then its name, address, course and marks can be grouped together to form the record for the student. File: A File is a collection of various records of one type of entity, for example, if there are 60 student in the class, then there will be 20 records in the related file where each record contains the data about each student. Attribute and Entity: An entity represents the class of certain objects. it contains various attributes. Each attribute represents the particular property of that entity. Field: Field is a single elementary unit of information representing the attribute of an entity.
  • 5. Need of Data Structures Processor speed: To handle very large amount 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.
  • 6.
  • 8. Classification of Data Structure · Primitive data structures · Non-primitive data structures (linear and non-linear) · Homogeneous and non-homogeneous data structures · Static and dynamic data structures
  • 9.
  • 10. 1. Primitive data structures :  Basic data structures and are directly operated upon by the machine instructions.  Classified into - integers, floating point numbers, characters, string constants, pointers etc. Like: int a =10; The corresponding machine level code will be like: store the int value in so and so location. But if I write: int arr[10]=20; The machine instruction doesn’t know array index 10! So, intermediate steps will be there to convert this particular instruction to machine level.
  • 11. 2. Non-primitive data structures: It is advanced data structure emphasizing on structuring of a group of data items. They cannot be directly operated upon by the machine instructions. Example: Array, list, files, linked list, trees and graphs fall in this category. Linear and non-linear data structures : In a linear data structure, the data items are arranged in a linear sequence. For example: array. In a non-linear data structure, the data items are not in sequence. For Example: trees and graphs.
  • 12. Cont’ Linear and non-linear data structures : In a linear data structure, the data items are arranged in a linear sequence. For example: array. In a non-linear data structure, the data items are not in sequence. For Example: trees and graphs.
  • 13. 3. Homogeneous and non- homogeneous data structures: In homogeneous data structure, all the elements are of same type. For Example: arrays. In non-homogeneous data structure, the elements may or may not be of the same type. For Example: Records.
  • 14. 4. Static and dynamic data structures: In Static data structure the size of the structure is fixed. The content of the data structure can be modified but without changing the memory space allocated to it. Example: Array In Dynamic data structure the size of the structure is not fixed and can be modified during the operations performed on it.  Dynamic data structures are designed to facilitate change of data structures in the run time. Example: Linked List
  • 15. Operations on Data Structures 1) Create:- The create operation results in reserving memory for program elements. This can be done by declaration statement. Creation of data structure may take place either during compile-time or run-time.  Dynamic Memory Allocation in C can be done using malloc(), calloc(), free() and realloc() 2) Destroy:- Destroy operation destroys memory space allocated for specified data structure. free() function of C language is used to destroy data structure. 3) Selection:- Selection operation deals with accessing a particular data within a data structure. 4) Updation:- It updates or modifies the data in the data structure. 5) Searching:- It finds the presence of desired data item in the list of data items, it may also find the locations of all elements that satisfy certain conditions. 6) Sorting:- Sorting is a process of arranging all data items in a data structure in a particular order, say for example, either in ascending order or in descending order. 7) Merging:- Merging is a process of combining the data items of two different non-primitive data structure into a single one. 8) Splitting:- Splitting is a process of partitioning single non-primitive data structure to multiple ones. 9) Traversal:- Traversal is a process of visiting each and every node of a non-primitive data structure in systematic manner.
  • 16. UNIT – I Dynamic Memory Allocation Part II
  • 18. Static memory allocation In Static Memory Allocation the memory for your data is allocated when the program starts. The size is fixed when the program is created. This memory allocation is fixed and cannot be changed, i.e. increased or decreased after allocation. So, exact memory requirements must be known in advance. Key features: · Variables get allocated permanently · Allocation is done before program execution · It uses the data structure called stack for implementing static allocation · There is no memory reusability Example: All the variables in the program below are statically allocated. void play { int a; } int main() { int b; int c[10]; return 1; }
  • 19. Static memory allocation the address can be obtained by using ‘&’ operator and can be assigned to a pointer. The memory is allocated during compile time. It uses stack for maintaining the static allocation of memory. In this allocation, once the memory is allocated, the memory size cannot change. It is less efficient.
  • 20. Dynamic memory allocation  C is a structured language, it has some fixed rules for programming. One of it includes changing the size of an array. An array is collection of items stored at continuous memory locations. Procedure refer as dynamic allocation a procedure in which the size of a data structure is changed during the runtime. Dynamic allocation is useful when data structures need to be created whose size is not known until run time
  • 21. Dynamic memory Allocating memory dynamically. While programming, if you are aware of the size of an array, then it is easy and you can define it as an array. Example Code Output. ... Resizing Memory Locations
  • 22. Library functions C provides some functions to achieve these tasks. There are 4 library functions provided by C defined under <stdlib.h> header file to facilitate dynamic memory allocation in C programming. They are: 1. malloc() 2. calloc() 3. free() 4. realloc()
  • 23. malloc(): “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. Syntax: ptr = (cast-type*) malloc(byte-size) For Example: ptr = (int*) malloc(100 * sizeof(int)); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And, the pointer ptr holds the address of the first byte in the allocated memory.
  • 24. calloc “calloc” or “contiguous allocation” method in C is used to dynamically allocate the specified number of blocks of memory of the specified type. It also returns a pointer of type void which can be cast into a pointer of any form. It initializes each block with a default value ‘0’. Syntax: ptr = (cast-type*)calloc(n, element-size); For Example: ptr = (float*) calloc(25, sizeof(float)); This statement allocates contiguous space in memory for 25 elements each with the size of the float.
  • 25. realloc() “realloc” or “re-allocation” method in C is used to dynamically change the memory allocation of a previously allocated memory. In other words, if the memory previously allocated with the help of malloc or calloc is insufficient, realloc can be used to dynamically re-allocate memory. Syntax: ptr = realloc(ptr, newSize); where ptr is reallocated with new size 'newSize'
  • 26. Free “free” method in C is used to dynamically de-allocate the memory. The memory allocated using functions malloc() and calloc() is not de-allocated on their own. Hence the free() method is used, whenever the dynamic memory allocation takes place. It helps to reduce wastage of memory by freeing it. Syntax: free(ptr);
  • 28. Recursion Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. Use - to solve many mathematical problems, such as calculating the factorial of a number, generating Fibonacci series, etc. void recursion() { recursion(); /* function calls itself */ } int main() { recursion(); }
  • 29. Types Recursion are mainly of two types depending on whether a function calls itself from within itself or more than one function call one another mutually. Types: Direct recursion Indirect recursion Direct Recursion: ◦ Tail Recursion ◦ If a recursive function calling itself and that recursive call is the last statement in the function ◦ Head Recursion ◦ If a recursive function calling itself and that recursive call is the first statement in the function ◦ Tree Recursion ◦ First understand linear recursion. If a recursive function calling itself for one time then it’s known as Linear Recursion ◦ Otherwise if a recursive function calling itself for more than one time – tree recursion ◦ Nested Recursion ◦ a recursive function will pass the parameter as a recursive call -“recursion inside recursion
  • 30. Cont’ Indirect recursion there may be more than one function and they are calling one another in a circular manner.
  • 32. Binomial coefficient Algorithm Step1: Start Step2: Accept two numbers n and r Step3: If n<r Print “Invalid input” Else Print result End if Step4: Stop Algorithm for BC(x) Step1: If x=0 return 1 Else return BC(n-1,r-1) + BC(n-1,r) End if
  • 33. Binomial Coefficient //Program to find Binomial Coefficient #include<stdio.h> int main() { int n,r; printf("Enter n value : "); scanf("%d",&n); printf("Enter r value : "); scanf("%d",&r); if(n<r) { printf("n Invalid input n value must be greater than r value"); } else { printf("Binomial coefficientn",BC(n,r)); printf("%dn",BC(n,r)); return 0; } } int BC(int n, int r) { if(r==0 || r==n) return 1; return BC(n-1,r-1) + BC(n-1,r); } Output: Enter n value : 3 Enter r value :6 Invalid input n value must be greater than r value Enter n value : 4 Enter r value :2 Binomial coefficient 6
  • 34. GCD Program to find GCD of two numbers using recursion Algorithm Step1: Start Step2: Accept two numbers m and n Step3: Call the function gcd(m,n) Step4: Print the result Step5: Stop Algorithm for gcd(a,b) Step1: If a==b return (a) else if(a>b) return(gcd(a-b,b) else return (gcd(a,b-a) End if #include<stdio.h> int gcd(int,int); void main() { int m,n; printf("nGreatest Common Divisorn"); printf("Enter the value for m : "); scanf("%d",&m); printf("Enter the value for n : "); scanf("%d",&n); printf("The Greatest Common Divisor of %d and %d = %d",m,n,gcd(m,n)); } int gcd(int a,int b) { if(a==b) { return(a); } else { if(a>b) return(gcd(a-b,b)); else return(gcd(a,b-a)); }
  • 35. Fibanacci series #include<stdio.h> #include<conio.h> int recursivefibonacci(int); int main(){ int m, x; printf("Please enter the total number of values you want in the Fibonacci series : n"); scanf("%d",&m); printf("The Fibonacci series of these numbers would be equal to : n"); for(x=0;x<m;x++) { printf("%d",recursivefibonacci(x)); } getch(); } int recursivefibonacci(int x){ if(x==0) return 0; else if(x==1) return 1; else return (recursivefibonacci(x-1) + recursivefibonacci(x- 2)); } Please enter the total number of values you want in the Fibonacci series : 4 The Fibonacci series of these numbers would be equal to : 0112 Output: Please enter the total number of values you want in the Fibonacci series : 4 The Fibonacci series of these numbers would be equal to : 0112
  • 36. Tower of hanoi Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more than one rings is as depicted − These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one sits over the larger one. The objective of the puzzle is to move the entire stack to the last rod, obeying the following rules: Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack or on an empty rod. No disk may be placed on top of a disk that is smaller than it. With 3 disks, the puzzle can be solved in 7 moves. The minimal number of moves required to solve a Tower of Hanoi puzzle is 2n − 1, where n is the number of disks.
  • 39. #include<stdio.h> void TOH(int n,char x,char y,char z) { if(n>0) { TOH(n-1,x,z,y); printf("n%c to %c",x,y); TOH(n-1,z,y,x); } } int main() { int n; scanf("%d",&n); TOH(n,'A','B','C'); }
  • 40. Program #include<stdio.h> #include<math.h> void main() { int n; char A,B,C; void towers(int,char,char,char); // clrscr(); printf("nTowers of Hanoin"); printf("nEnter the number of disks : "); scanf("%d",&n); printf("The number of moves=%0.fn",(pow(2,n)-1)); printf("nTowers of Hanoi simulation for %d disksn",n); towers(n,'A','C','B'); getch(); } void towers(int n,char source,char dest,char aux) { if(n==1) { printf("nMove disk %d from %c to %c",n,source,dest); return; } towers(n-1,source,aux,dest); printf("nMove disk %d from %c to %c",n,source,dest); towers(n-1,aux,dest,source); }
  • 41. output Towers of Hanoi Enter the number of disks : 3 The number of moves=7 Towers of Hanoi simulation for 3 disks Move disk 1 from A to C Move disk 2 from A to B Move disk 1 from C to B Move disk 3 from A to C Move disk 1 from B to A Move disk 2 from B to C Move disk 1 from A to C Algorithm Step1: Start Step2: Input the number of disks Step3: Print the number of movements 2disk-1 Step4: Call the function towers(n,’A’,’C’,’B’) Step5:Stop Algorithm for towers(n,source,dest,aux) n is the total no. of disks and A, B, and C are the source, destination and intermediate pegs respectively. Step1: If n=1 Print the movement source to destination Else Step a: Call the function towers(n-1,source,aux,dest) Step b: Print the movement source to destination Step c: Call the function towers(n-1,aux,dest,source) End if