0% found this document useful (0 votes)
18 views21 pages

DS Chapter 1

The document provides an introduction to data structures, defining them as methods for organizing data in computer memory for efficient usage. It classifies data structures into primitive and non-primitive types, with further subdivisions into linear and non-linear structures, and discusses operations like insertion, deletion, and searching. Additionally, it covers memory allocation techniques, recursion, and compares recursive and iterative approaches.

Uploaded by

keerthinagraj6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views21 pages

DS Chapter 1

The document provides an introduction to data structures, defining them as methods for organizing data in computer memory for efficient usage. It classifies data structures into primitive and non-primitive types, with further subdivisions into linear and non-linear structures, and discusses operations like insertion, deletion, and searching. Additionally, it covers memory allocation techniques, recursion, and compares recursive and iterative approaches.

Uploaded by

keerthinagraj6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

DATA STRUCTURES

Unit: 01
INTRODUCTION TO DATA STRUCTURES

Introduction to data structure


A data structure is a Specific way to store and organize data in a computer's memory so that
these data can be used efficiently later. Data may be arranged in many different ways such as the
logical or mathematical model for a particular organization of data is termed as a data structure.
Definition
A data structure is particular way of organising data in a computer so that elements that it can be
used effectively.
The data structure is a group of data elements that provides easiest way to store & to perform
different operation on data.
Or
The logical / mathematical model of a particular organization of a data is called data structure.

Data structure is broadly classified into 2 types they are:


1. Primitive data structure / pre-defined data structure.
2. Non - primitive data structure / user defined data structure.

1. Primitive data structures are pre-defined data structure:


The data structure of primitive data structures is already defined in the system.
Examples: - int, float, char, double.
2. Non-primitive data structure or user-defined data structure:
Non primitive data structure is user-defined data structure. The non-primitive data structure is
classified into 2 types they are

Chithra T R Page 1
DATA STRUCTURES

1. Linear data structure: -


The elements which are access are placed in contagious over sequential memory
allocations is called linear data structure.
Examples: - arrays, stacks, queues linked list.
 Arrays: - it is a collection of data elements of same type or same name is called arrays.
Example: - int a[5];
10 a[0]
20 a[1]
30 a[2]
40 a[3]
50 a[4]

 Stacks: - it is a linear data structure, it uses the [LEFO] rule in which data added at the last will be
removed at the first.
 Queues: - it is a linear data structure, it uses the [FIFO] rule in which element added at the last and
remove at the first.
 Linked List: - it is a collection of NODES that are made up of two parts i.e., data and address of
next node.

2. Non-Linear Data Structure: - the elements which are accessed or placed in the non-contagious or
non-sequential way of memory allocation is called as non-linear data structure.
Non-linear data structure or classified into two types:
1. Trees: - it is a collection off nodes where these nodes are arranged hierarchically and form a parent
child relationship. Example: -

2. Graphs: - it is a collection of finite numbers of vertices and edges.


Example: -

Operations on Data Structures


The Data which is stored in our data structure or processed by some set of operations they are:
1. Inserting: Adding the new element to the existing data structure.
2. Deleting: Deleting the element from the data structure.
3. Traversing: Accessing each element exactly once is called traversing.
4. Searching: Arranging the elements in ascending or descending order.
5. Merging: Combining the two different lists into single list. Element
10 20 30 40 50 Address or
a[0] a[1] a[2] a[3] a[4] index

Chithra T R Page 2
DATA STRUCTURES

DIFFERENCES BETWEEN STATIC MEMORY ALLOCATION AND DYNAMIC


MEMORY ALLOCATION
STATIC MEMORY ALLOCATION DYNAMIC MEMORY ALLOCATION
1. In the static variables get allocated 1. In the variables get allocated only if your
permanently till the program executes. program unit gets active.
2. It executes at compile time. 2. It executes at run time.
3. It is done before program execution. 3. It is done during program execution.
4. It is less efficient. 4. It is more efficient.
5. There is no memory reusability. 5. There is memory reusability and memory
6. Once the memory is allocated the can be freed when elements are not
memory cannot be changed. assigned.
7. We cannot reuse the unused memory. 6. When memory is allocated the memory
8. It is faster than dynamic memory. size can be changed.
7. This allows the reusing the memory and
release the memory which is not used
8. It is slower than static memory

Dynamic Memory Allocation and De-Allocation Functions


Dynamic memory allocation functions are classified into 4 types, they are

1. Malloc ()
2. Calloc () Memory Allocation Functions
3. Realloc ()
4. Free () De-Allocation Function

 Malloc ()
 It stands for memory allocation.
 The function Malloc reserves a single block of memory that contains the number of bits Specified in
its parameter.
 The general syntax of Malloc is-
Ptr=(datatype*) malloc (byte size);
Program To Show Usage of Malloc Function.

#include<stdio.h>
#include<conio.h>
void main ()
{
int n,i,*ptr,sum=0;
clrscr();
printf(“Enter number of elements:”);
Scanf(“%d”,&n);

Chithra T R Page 3
DATA STRUCTURES

ptr=(int*)malloc(n*size of (int));
if(ptr==null)
{
printf(“\n Error ! Memory not allocated”);
exit(0);
}
printf(“\n Total memory allocated for %d elements are %d bytes”,n,n*sizeof(int));
printf(“Enter elements of array:\n”);
for(i=0;i<n;++i)
{
scanf(“%d”,ptr+i);
sum+=*(ptr+i);
}
printf(“sum=%d”,sum);
free(ptr);
getch();
}
Output:
Enter number of elements: 5
Total memory allocation for 5 elements are 10 bytes
Enter elements of array:
10 20 30 40 50
Sum = 15
 Calloc ()
 It stands for continuous memory allocation.
 It is primarily used to allocate the memory for arrays.
 The only difference between malloc and calloc is that malloc allocates single
 Block of memory whereas calloc allocates multiple blocks of memory.

 The general syntax of calloc is:


Ptr = calloc (element-count, element-size);

Chithra T R Page 4
DATA STRUCTURES

Program to show usage of calloc function.

#include<stdio.h>
#include<conio.h>
void main ()

{
int n,i,*ptr,sum=0;
clrscr();
printf(“Enter number of elements:”);
scanf(“%d”,&n);
ptr=(int*)calloc(n,size of (int));
if(ptr==null)
{
printf(“Error ! memory not allocated”);
exit(0);
}
printf(“\n Total memory allocated for %d elements is %d bytes”,n,n*size of(int));
printf(“\n Initial memory contents:”);
for(i=0 ;i<n;i++)
{
scanf(“%d”,ptr*i);
Sum+=*(ptr+i);
}
printf(“sum=%d”,sum);
free();
getch();
}
Output: Enter number of elements:4
Total memory allocated for 4 elements is 8 bytes.
Initial memory contents:0 0 0 0
Enter elements of array:10 20 30 40
Sum=10

Chithra T R Page 5
DATA STRUCTURES

 Realloc ():
 If a previously allocated memory insufficient or more than sufficient then this memory size can be
changed using this function.
 The general syntax is:
ptr=realloc(ptr,new size);

Program to show usage of relloc function.


#include<stdio.h>
#include<conio.h>
void main()
{
int*ptr,i,n1,n2;
clrscr();
printf(“Enter size of array:”);
scanf(“%d”,&n1);
ptr=(int*)malloc(n1*size of(int));
printf(“previously allocated memory address:”);
for(i=0;i<n1;i++)
printf(“%u\t”,ptr+i);
printf(“\n enter new size of array:”);
scanf(“%d”,&n2);
printf(“Newly allocated memory address:”);
ptr=realloc(ptr,n2);
for(i=0;i<n2;i++)
printf(“%u\t”,ptr+i);
getch();
}
Output:
Enter size of array:3
Previously allocated memory address:1958 1960 1962
Enter new size of array:4
Newly allocated memory address:1958 1960 1962 1964

Chithra T R Page 6
DATA STRUCTURES

 Free ():
 It stands for releasing the memory.
 It is a memory De-allocation function.
 When the memory allocations are allocated by malloc,calloc and realloc are no longer required then
they are freed using pre-defined function free.
 The general syntax of free function is:
free(ptr);
Recursion
 A Function that calls itself is known as recursion function
 The process of calling a function by itself
Syntax: - returntype recursivefunction name(arguments/parameters);
{
Statements;
Recursive function name(arguments/parameters);
}
Ex: - int factorial(int x)
{
if(x = = 0)
{
return 1;
}
else
{
return(x*factorial(x-1));
}
}
Advantages of recursion: -
1. Recursion reduces length of the code
2. Recursion reduces the unnecessary calling of function
3. Recursion is very useful in solving data structure problems
4. We can solve problems by using simple way
5. In recursion code is simple and short than iterative code
Disadvantages of recursion: -
1. Recursion programs are generally slower than iterative
2. Recursive program requires more memory
3. Recursion uses more CPU processing time
4. Recursion programs are a bit difficult to understand and debug

Chithra T R Page 7
DATA STRUCTURES

Applications of recursion: -
1. To compute factorial of a number
2. Towers of Hanoi
3. All searching techniques uses recursive techniques(Linear search and Binary search)
4. Candy crush game uses recursion
5. We use recursion to determine whether a string is palindrome or not
6. Stack uses recursion technique

Chithra T R Page 8
DATA STRUCTURES

Chithra T R Page 9
DATA STRUCTURES

Chithra T R Page 10
DATA STRUCTURES

Types of recursions: -
There are 2 types of recursions, they are
1. Direct Recursion
2. Indirect Recursion

1. Direct Recursion: - If a function explicity call Same function by itself then that type of recursion
is called as direct recursion

Ex: - int GCD(int a ,int b)


{
if(b = = 0)
{
return a;
}
else
{
return GCD(b,a%b);
}
}

2. Indirect recursion: - If a function calls another function which again calls the original function then
that type of recursion is called indirection recursion

Ex: - int function 1(int n)


{
if (n = = 1)
{
return 1;
}
else
{
return function 2(n);
}
}
int function 1(int n)
{
return function(n);
}

Program to implement factorial of a number using recursion


#include<stdio.h>
#include <conio.h>
int factorial(int);
void main()
{
Chithra T R Page 11
DATA STRUCTURES

int n,fact;

Chithra T R Page 12
DATA STRUCTURES

clrscr();
printf(“Enter the values \n”);
scanf(“%d”,&n);
fact=factorial(n);
printf(“the factorial of given number %d is %d”,n,fact);
getch();
}
int factorial(int n)
{
if(n==0)
{
return 1;
}
else
{
return n*factorial(n-1);
}
}
Output: -
Enter the value:
7
The factorial of given number 7 is 5040

Difference between Iterative and Recursion


Recursion Iterative

Chithra T R Page 13
DATA STRUCTURES

1. Recursion can be defined as a function 1. Iteration can be defined as when a loop


called by itself repeatedly repeatedly executes a set of instructions
2. Recursion is a process always applied to a until the condition becomes false
function 2. Iteration is applied to the set of instructions
3. Recursion reduces the size of code which we want to get repeatedly executed the
4. Recursion is slow in execution statements in loop
5. A conditional statement decides the 3. Iteration makes code longer
termination of recursion 4. Iteration is fast in execution
6. The stack is used to implement the recursion 5. Control variable value decides the
7. Infinite recursion can lead to system crash termination of iteration statements
8. Recursive function is easy to write 6. Iteration does not use stack
9. Ex: int gcd(int a, 7. Infinite loops use cpu cycles repeatedly
int b) 8. Iteration function statements are bit harder
{ to write

Chithra T R Page 14
DATA STRUCTURES

if(b==0) 9. Ex:
{ while(condition)
return a; {
} statements(s);
else statements(s);
{ }
return gcd(b,a%b);
}
}

Recursion Technique Example


There are 3 types of recursive technique, they are
1. Greatest Common Divisor (GCD).
2. Binomial Co-efficient of NCR.
3. Towers of Hanoi.
1. Greatest common divisor: In this program it is helpful to classify the greatest common factor
between two numbers is called as greatest common factor.
For example: The gcd of 15 and 5 is 5, since both the numbers can be divided by 5.the condition is
that the numbers should be non-zero.

//Program to find the GCD of two numbers


#include<stdio.h>
#include<conio.h>
int gcd(int,int);
void main()
{
int a,b,result;
clrscr();
printf(“enter a and b:\n”);
scanf (“%d%d”,&a,&b);
result=gcd(a,b);
printf(“GCD of %d and %d is %d”,a,b, result);
getch();
}
int gcd(int p,int q)
{
if(q==0)
{
return p;
}
else
{
return(gcd(q,p%q));
}}
Output:
Enter a and b:
40 60

Chithra T R Page 15
DATA STRUCTURES

GCD of 40 and 60 is 20

Chithra T R Page 16
DATA STRUCTURES

2. Binomial Coefficient [n c r]
The binomial coefficient of NCR is also called as pascals triangle. It begins from sum of 2 numbers to power
zero to given values at the runtime. A binomial is a polynomial expression that contains exactly 2 terms. A
binomial can be considered as a sum or difference between two or more monomials.
//Program to display Pascal’s triangle using Binomial function.
#include <stdio.h>
#include <conio.h>
void main ()
{
int rows, a, s, coef = 1, i, j;
clrscr();
printf("\n\t\t\t Pascal’s Triangle ");
printf("\n\nEnter The Number of Rows : ");
scanf("%d", &rows);
for (i = 0; i < rows; i++)
{
for (s = 0; s <= rows - i; s++)
printf(" ");
for (j = 0; j <= i; j++)
{
if (j == 0 || i == 0)
{
coef = 1;
}
else
{
coef = coef * (i - j + 1) / j;
}
printf("%4d", coef);
}
printf("\n\n");
}

Chithra T R Page 17
DATA STRUCTURES

getch();

Chithra T R Page 18
DATA STRUCTURES

}
Output:

3. Towers of Hanoi
The Towers of Hanoi is a mathematical puzzle with set of rules its just replacing a ring into three poles
without placing the small ring on larger ring and even transferring the both ring at once. Each can be placed
only once in each step. At the output of this program, it gives the number of steps to be followed to complete
the puzzle.
(Or)
The Towers of Hanoi is a mathematical puzzle it consists of three rods and n number of disks of different
size which can slide onto any rod. The objective of the puzzle is to move the entire disk stack to another rod,
obeying the following simple rules.
POLES
1) Source pole (from pole)
2) Auxiliary pole
3) Destination pole (to pole)
There are three rules to solve problem of towers of Hanoi they are:
1. Only one disk can be move at a time
2. No disk may be placed on top of a smaller disk
3. We can use an auxiliary tower for temporary storage of disk

An example with 3 disks:


Step 1: Shift first disk from 'A' to 'C'.
Step 2: Shift second disk from 'A' to 'B'.
Step 3: Shift first disk from 'C' to 'B'.
Step 4: Shift third disk from 'A' to 'C'.
Step 5: Shift first disk from 'B' to 'A'.
Step 6: Shift second disk from 'B' to 'C'.
Step 7: Shift first disk from 'A' to 'C'.
Chithra T R Page 19
DATA STRUCTURES

Write a program to implement “Towers of Hanoi”


#include<stdio.h>
#include<conio.h>
void towers(int,char,char,char)
void main()
{
int n;
clrscr();
printf(“enter the number of discs:\n”);
scanf(“%d”,&n);
printf(“sequence of moves involved in the towers of hanoi problem:\n”);
towers(n,’A’,’C’,’B’);
getch();
}
void towers(int n, char from_pole, char to_pole, char aux_pole)
{
if(n==1)
{
printf(“\n move disc 1 from pole %c to pole %c \n, from_pole, to_pole);
return;
}
else
{
towers(n-1,from_pole,aux_pole,to_pole);
printf(“\n move disc %d from pole %c, to_pole %c \n”,n, from_pole, to_pole);
towers(n-1,aux_pole,to_pole,from_pole);
}
}

Chithra T R Page 20
DATA STRUCTURES

Output:
Enter the number of discs:
3
sequence of moves involved in the Towers of Hanoi problem:
move disc 1 from pole A to pole C
move disc 2 from pole A to pole B
move disc 1 from pole C to pole B
move disc 3 from pole A to pole C
move disc 1 from pole B to pole A
move disc 2 from pole B to pole C
move disc 1 from pole A to pole C

Chithra T R Page 21

You might also like