0% found this document useful (0 votes)
199 views71 pages

C++ Unit-2

The document discusses data structures and provides information on various types of data structures. It defines data structures as organized data and operations. It describes some key advantages of data structures like efficiency and reusability. It then classifies data structures as primitive and non-primitive. Primitive data structures directly operate on machine instructions while non-primitive are more complex structures derived from primitive ones. The document further discusses various types of data structures like arrays, linked lists, stacks, queues, trees and graphs. It provides information on operations for primitive and non-primitive data structures.

Uploaded by

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

C++ Unit-2

The document discusses data structures and provides information on various types of data structures. It defines data structures as organized data and operations. It describes some key advantages of data structures like efficiency and reusability. It then classifies data structures as primitive and non-primitive. Primitive data structures directly operate on machine instructions while non-primitive are more complex structures derived from primitive ones. The document further discusses various types of data structures like arrays, linked lists, stacks, queues, trees and graphs. It provides information on operations for primitive and non-primitive data structures.

Uploaded by

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

DATA STRUCTURES

Defination : “It is used to store data in an organized and efficient manner.”


OR
“ Logical or Mathematical model of an particular organization of data is called Data
Structure”

The C Programming language has many data structures like an array, stack,


queue, linked list, tree, etc. A programmer selects an appropriate data
structure and uses it according to their convenience.
D.S = Organised Data + Operation

1
ADVANTAGES OF DATA STRUCTURES

 Efficiency – Proper choice of DS make program in terms of Time and Space.


 Reusability – One implementation can be used by many client program.
 Abstraction – The client program doesn’t have worry about implementation details.

2
CLASSIFICATIONS (PRIMITIVE & NON PRIMITIVE),

3
Data Structure

Primitive Non-Primitive

Integer
Linear Non Linear
Float
Character
Pointer

Arrays Linked List Stacks Queues

Tress Graphs Tables Sets


PRIMITIVE AND NON-PRIMITIVE DATA STRUCTURES
Primitive Data Structures
Primitive Data Structures are the basic data structures that directly operate upon the machine instructions. They have
different representations on different computers.
Integers, Floating point numbers, Character constants, String constants and Pointers come under this category

Non-primitive Data Structures


Non-primitive data structures are more complicated data structures and are derived from primitive data structures.
They emphasize on grouping same or different data items with relationship between each data item.
Arrays, Lists and Files come under this category.

5
CLASSIFICATION OF DATA STRUCTURES
Types of Data Structures Based on relationship between data elements
The below categories is under Non-Primitive Data Structures.
1. Linear data structure
2. Non-Linear data structure

6
CLASSIFICATION OF DATA STRUCTURE

7
CLASSIFICATION OF DATA STRUCTURES

Static Data Structure

DYNAMIC DATA STRUCTURE

8
NON-HOMOGENEOUS/ HETEROGENEOUS

Homogeneous data: Homogeneous data structures are those data structures that contain
only similar type of data e.g. like a data structure containing only integer or float values.
The simplest example of such type of data structures is an Array.

Heterogeneous Data: Heterogeneous Data Structures are those data structures that


contains a variety or dissimilar type of data, for e.g. a data structure that can contain
various data of different data types like integer, float and character. The examples of such
data structures include structures, union, records, classes etc

9
Data Structures may also be classified as
1. Static Data Structures
2. Dynamic Data Structures
Static 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 of Static Data Structures: Array
Dynamic Data Structures : In Dynamic data structure the size of the structure in 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 of Dynamic Data Structures: Linked List

10
OPERATIONS ON PRIMITIVE DATA STRUCTURES

Primitive data types are predefined types of data, which are supported by the


programming language. For example, integer, character, and string are
all primitive data types. 
Non-primitive data type: Non-primitive data types are not defined by the
progr.amming language, but are instead created by the programmer

Operations on primitive Data Structures :


 Creation
 Selection
 Update or Modify
 Delete or Destroy

11
OPERATIONS ON NON-PRIMITIVE DATA STRUCTURES

Non Primitive Data Structure operations :

 Traversal
 Insertion
 Deletion
 Sorting
 Searching
 Merging

12
ARRAYS
 Array is the collection of similar data types Arrays can be single or multidimensional. The number
or collection of similar entity stored in of subscript or index determines the dimensions of
contiguous memory location. the array.
 Array of character is a string. Each data An array of one dimension is known as a one-
item of an array is called an element. And dimensional array or 1-D array, while an array of
each element is unique and located in two dimensions is known as a two-
separated memory location. Each of dimensional array or 2-D array.
elements of an array share a variable but
each element having different index no. NOTE:
known as subscript. • Arrays index will starts with zero
• arrays will occupy contigeous memory locations.
TYPES OF ARRAYS

Arrays can be classified into following types INITIALIZATION OF AN ARRAY


1. One dimensional array.  After declaration element of local array has
garbage value. If it is global or static array then it
2. Two dimensional array. will be automatically initialize with zero.
3. Multi dimensional array.  An explicitly it can be initialize that Data type
One dimensional array  Array_name [size] = {value1, value2, value3…}
Syntax  Example: in ar[5]={20,60,90,100,120}
type variable_name[size]
Eg:  Total size in byte for 1D array is
int arr[100];
char name[25]; Total_bytes=size of (data type) * size of array.
ONE-DIMENSIONAL ARRAY
TYPES OF ARRAYS

Arrays can be classified into following types INITIALIZATION OF AN ARRAY


1. One dimensional array.  After declaration element of local array has
garbage value. If it is global or static array then it
2. Two dimensional array. will be automatically initialize with zero.
3. Multi dimensional array.  An explicitly it can be initialize that Data type
One dimensional array  Array_name [size] = {value1, value2, value3…}
Syntax  Example: in ar[5]={20,60,90,100,120}
type variable_name[size]
Eg:  Total size in byte for 1D array is
int arr[100];
char name[25]; Total_bytes=size of (data type) * size of array.
INSERTION OPERATION - INSERT AN ELEMENT IN AN
ARRAY
An array is a collection of items stored at contiguous memory locations. In this article, we
will see how to insert an element in an array in C.
Given an array arr of size n, this article tells how to insert an element x in this array arr at a
specific position pos.
Approach:
Here’s how to do it.
First get the element to be inserted, say x
Then get the position at which this element is to be inserted, say pos
Then shift the array elements from this position to one position forward, and do this for all
the other elements next to pos.
Insert the element x now at the position pos, as this is now empty. Program :

17
COURSE OUTCOMES:

18
PROGRAM TO DELETE AN ELEMENT FROM ARRAY IN C

19
ARRAYS – 2D ARRAYS

Arrays can be single or multidimensional. The number of subscript or index


determines the dimensions of the array.
An array of one dimension is known as a one-dimensional array or 1-
D array, while an array of two dimensions is known as a two-
dimensional array or 2-D array.

NOTE:
• Arrays index will starts with zero
• arrays will occupy contigeous memory locations.
TWO DIMENSIONAL ARRAYS
Two dimensional array is known as matrix. // Different ways to initialize two-
The array declaration in both the array i.e. in
dimensional array
single dimensional array single subscript is
used and in two dimensional array two int x[5][5]={4,6,8,3,5,7}
subscripts are is used. int c[2][3] = {{1, 3, 0}, {-1, 5, 9}};
Syntax int c[][3] = {{1, 3, 0}, {-1, 5, 9}};
variable_name[row][column]; int c[2][3] = {1, 3, 0, -1, 5, 9};
Eg: int x[3][4];
ARRAYS – 2D ARRAYS

Memory Representation of 2-D array Here, x is a two-dimensional (2d) array.


The array can hold 12 elements. You
can think the array as a table with 3
rows and each row has 4 columns.
Program to find sum of 2 matrix:
Program:
Assignment:
Program to find
i. product of 2 matrix
ii. Trace and Norm of matrix
iii. Identity matrix
iv. Transpose of given matrix
STRINGS OPERATIONS

A string is a sequence of characters terminated with a NULL(‘\0’) character.


char str[] = "c string";
When the compiler encounters a sequence of characters enclosed in the double quotation
marks, it appends a null character \0 at the end by default.
INITIALIZE OF STRINGS

Initialize strings in a number of ways. char c[5] = "abcde";


char c[] = "abcd"; Here, we are trying to assign 6 characters
char c[50] = "abcd"; (the last character is '\0') to a char array
having 5 characters. This is example we
char c[] = {'a', 'b', 'c', 'd', '\0'}; can store only 5 characters.
char c[5] = {'a', 'b', 'c', 'd', '\0'};
Assigning Values to Strings
Memory diagram of strings char c[100];
c = "C programming";
// Error! array type is not assignable
STRING HANDLING FUNCTIONS
STRING LIBRARY FUNCTION

There are several string library functions used It accepts a single argument which is
to manipulate string and the prototypes for pointer to the first character of the
these functions are in header file “string.h”. string.
Several string functions are Ex: strlen(“suresh”);
strlen()  It return the value 6.
 This function return the length of the string. i.e. void main() 
the number of characters in the string excluding {
the terminating NULL character. char str[50];
print(”Enter a string:”);
Syntax: strlen(string);
gets(str);
printf(“Length of the string is %d\
n”,strlen(str));
}
OVERVIEW OF STRUCTURES UNION
Structure : It is the collection of dissimilar data types or heterogeneous data types
grouped together. It means the data types may or may not be of same type.
Syntax : struct tag_name
{ Data type member1;
Data type member2;
Data type member3;
……… ………
Data type member n;
};
INITIALIZATION OF STRUCTURE VARIABLE

Like primary variables structure struct student


variables can also be initialized when
they are declared. {

Structure templates can be defined int age,roll;


locally or globally. If it is local it can be char name[20];
used within that function. If it is global
it can be used by all other functions of };
the program. struct student s1={16,101,”sona”}; struct
We cant initialize structure members student s2={17,102,”rupa”};
while defining the structure
ACCESSING STRUCTURE ELEMENTS

Dot operator is used to access the Array of structures :


structure elements. Its associativity is When database of any element is used in
from left to right structure variable. huge amount, we prefer Array of
s1.name[]; structures.
s1.roll; Example: suppose we want to maintain
s1.age; data base of 200 students, Array of
Elements of structure are stored in structures is used.
contiguous memory locations. Value of
structure variable can be assigned to Program :
another structure variable of same type
using assignment operator.
Example:
NESTED STRUCTURE
struct date
When a structure is within another structure, it is {
called Nested structure. A structure variable can int date,month;
be a member of another structure and it is };
represented as struct student
It is possible to define structure outside & declare {
its variable inside other structure. char nm[20];
int roll;
 Array of structure struct date d;
 Array within the structure };

 Passing structure elements to function struct student s1;


struct student s2,s3;
Program
UNION
Union is derived data type contains collection of Syntax of union:
different data type or dissimilar elements. union Tag_name
{
All definition declaration of union variable and datatype member1;
accessing member is similar to structure, but datatype member2;
instead of keyword struct the keyword union is };
used.
The main difference between union and Eg:
structure is, each member of structure occupy union student
the uniq memory location, but in the unions { int rollno;
members share memory. Union is used for char name[25]
saving memory and concept is useful when it is }s1;
not necessary to use all members of union at a
time. Initialization :
union student s1={16,101,”sona”};
DIFFERENCE BETWEEN STRUCTURE AND UNION
Linear Data Structures: Stack

SC HOOL OF C S A , R E VA U n i v e r s i t y
Deep a B G
STACK

 Stack is a special type of data structure where elements are inserted and deleted from
the same end.
 It is named stack as it behaves like a real-world stack, for example – a deck
of cards or a pile of plates, etc.

 For example, we can place or remove a card or plate from the top of the
stack only. Likewise, Stack ADT allows all data operations at one end only. At
any given time, we can only access the top element of a stack.

34
This feature makes it LIFO data structure. LIFO stands for Last-in-first-out. Here, the element which is placed
(inserted or added) last, is accessed first. In stack terminology, insertion operation is called PUSH operation
and removal operation is called POP operation.

Stack Representation

The following diagram depicts a stack and its operations −

35
OPERATIONS ON STACK

• push() − Pushing (storing) an element on the stack.


• pop() − Removing (accessing) an element from the stack
To use a stack efficiently, we need to check the status of stack as well. For the
same purpose, the following functionality is added to stacks −
• peek() − get the top data element of the stack, without removing it.
• isFull() − check if stack is full.
• isEmpty() − check if stack is empty.

36
PUSH OPERATION

 The process of putting a new data element onto stack is known as a Push
Operation. Push operation involves a series of steps −

• Step 1 − Checks if the stack is full.


• Step 2 − If the stack is full, produces an error and exit.
• Step 3 − If the stack is not full, increments top to point next empty space.
• Step 4 − Adds data element to the stack location, where top is pointing.
• Step 5 − Returns success.

37
PUSH OPERATION CONTD..

If the linked list is used to implement the stack, then in step 3, we need to allocate space dynamically

38
Programming Logic

void push(int data)


{
if(! isFull())
{
top = top + 1;
stack[top] = data;
}
Else
{
cout<<"Could not insert data, Stack is full”<<”\n";
}
}

39
POP OPERATION

 The procedure of removing element from the top of the stack is called pop
operation.
 Only one element can be deleted from stack at a time and element has to be deleted
only from the top of the stack.
 When elements are being deleted, there is a possibility of stack being empty.
 When stack is empty, it is not possible to delete any element.
 Trying to delete an element from an empty stack results in stack underflow.
 After every pop operation, the value of TOP is decremented by one.

40
POP OPERATION
 A Pop operation may involve the following steps −
• Step 1 − Checks if the stack is empty.
• Step 2 − If the stack is empty, produces an error and exit.
• Step 3 − If the stack is not empty, accesses the data element at
which top is pointing.
• Step 4 − Decreases the value of top by 1.
• Step 5 − Returns success.

41
PROGRAMMING LOGIC

int pop(int data)


{
if(!isempty())

{
data = stack[top];
top = top - 1;
return data;
}
else
{
cout<<"Could not retrieve data, Stack is empty”<<“\n");
}
}
42
Peek operation
At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer always represents
the top of the stack, hence named top. The top pointer provides top value of the stack without actually
removing it.

Example
int peek()
{
return stack[top];
}

43
bool isfull()
{
isfull() if(top == MAXSIZE)
return true;
Else
return false; }
isempty()
Implementation of isempty() function in C programming language is slightly different. We initialize top at -1, as
the index in array starts from 0. So we check if the top is below zero or -1 to determine if the stack is empty.
bool isempty()
{
if(top == -1)
return true;
else
return false;
} 44
STACK APPLICATIONS: INFIX TO POSTFIX CONVERSION
CONTD..
Infix Expression
It follows the scheme of <operand><operator><operand> i.e. an <operator> is
preceded and succeeded by an <operand>. Such an expression is termed infix
expression.
E.g., A+B

Postfix Expression
It follows the scheme of <operand><operand><operator> i.e. an <operator> is
succeeded by both the <operand>.
E.g., AB+
45
ALGORITHM TO CONVERT INFIX TO POSTFIX
1. Let, X is an arithmetic expression written in infix notation. This algorithm finds the equivalent postfix expression Y.

2. Push “(“onto Stack, and add “)” to the end of X.

3. Scan X from left to right and repeat Step 3 to 6 for each element of X until the Stack is empty.

4. If an operand is encountered, add it to Y.

5. If a left parenthesis is encountered, push it onto Stack.

6. If an operator is encountered ,then:

1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) which has the same precedence as or higher precedence
than operator.

2. Add operator to Stack.


[End of If]

7. If a right parenthesis is encountered ,then:

1. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left parenthesis is encountered.

2. Remove the left Parenthesis.


[End of If]
[End of If]

8. END.

46
EXAMPLE:

47
PROGRAM to convert infix to postfix expression

48
LECTURE 7

Recap Topics to be covered

Stack applications Stack applications


-Towers of Hanoi Evaluation of postfix expression
Reversal of a string
STACK APPLICATIONS: EVALUATION OF POSTFIX
EXPRESSION
A postfix expression is a collection of operators and operands in which the operator is
placed after the operands. That means, in a postfix expression the operator follows the
operands.

Postfix Expression has following general structure...


Operand1 Operand2 Operator

50
POSTFIX EXPRESSION EVALUATION USING STACK DATA
STRUCTURE
1. A postfix expression can be evaluated using the Stack data structure. To evaluate a
postfix expression using Stack data structure we can use the following steps...
2. Read all the symbols one by one from left to right in the given Postfix Expression
3. If the reading symbol is operand, then push it on to the Stack.
4. If the reading symbol is operator (+ , - , * , / etc.,), then perform TWO pop
operations and store the two popped operands in two different variables (operand1
and operand2). Then perform reading symbol operation using operand1 and
operand2 and push result back on to the Stack.
5. Finally! perform a pop operation and display the popped value as final result.

51
EXAMPLE:

52
EXAMPLE: CONTD..

53
54
Linear Data Structures: Queue

SC HOOL OF C S A , R E VA U n i v e r s i t y
Deep a B G
LECTURE 1

Recap Topics to be covered

Selection Sort  Queue


57
Queue is an abstract data structure, somewhat similar to Stacks. Unlike stacks, a queue is open at
both its ends.  in which the first element is inserted from one end called the REAR(also called tail), and the
removal of existing element takes place from the other end called as FRONT(also called head).

58
BASIC FEATURES OF QUEUE

1. Like stack, queue is also an ordered list of elements of similar data types.
2. Queue is a FIFO( First in First Out ) structure.
3. Once a new element is inserted into the Queue, all the elements inserted before the
new element in the queue must be moved front.
4. peek( ) function is oftenly used to return the value of first element without
dequeuing it.

59
APPLICATIONS OF QUEUE

Queue, as the name suggests is used whenever we need to manage any group of objects
in an order in which the first one coming in, also gets out first while the others wait for
their turn, like in the following scenarios:
1. Serving requests on a single shared resource, like a printer, CPU task scheduling etc.
2. In real life scenario, Call Center phone systems uses Queues to hold people calling
them in an order, until a service representative is free.
3. Handling of interrupts in real-time systems. The interrupts are handled in the same
order as they arrive i.e First come first served.

60
IMPLEMENTATION OF QUEUE DATA STRUCTURE

Queue can be implemented using an Array, Stack or Linked List.


The easiest way of implementing a queue is by using an Array.

• Initially the head(FRONT) and the tail(REAR) of the queue points at the first


index of the array (starting the index of array from 0).
• As we add elements to the queue, the tail keeps on moving ahead, always
pointing to the position where the next element will be inserted, while
the head remains at the first index.
• we remove the element from head position and then move head to the
next position.

61
BASIC OPERATIONS

Queue operations may involve initializing or defining the queue, utilizing it, and then
completely erasing it from the memory. Here we shall try to understand the basic
operations associated with queues −
1. enqueue() − add (store) an item to the queue.
2. dequeue() − remove (access) an item from the queue.
Few more functions are required to make the above-mentioned queue operation efficient.
These are −
3. peek() − Gets the element at the front of the queue without removing it.
4. isfull() − Checks if the queue is full.
5. isempty() − Checks if the queue is empty.

62
ALGORITHM FOR ENQUEUE OPERATION
Queues maintain two data pointers, front and rear. Therefore, its operations are
comparatively difficult to implement than that of stacks.
The following steps should be taken to enqueue (insert) data into a queue −
1. Step 1 − Check if the queue is full.
2. Step 2 − If the queue is full, produce overflow error and exit.
3. Step 3 − If the queue is not full, increment rear pointer to point the next empty
space.
4. Step 4 − Add data element to the queue location, where the rear is pointing.
5. Step 5 − return success.

63
64
IMPLEMENTATION OF ENQUEUE

int enqueue(int data)


if(isfull())
return 0;
rear = rear + 1;
queue[rear] = data;
return 1;
end procedure

65
ALGORITHM FOR DEQUEUE OPERATION

Accessing data from the queue is a process of two tasks − access the data
where front is pointing and remove the data after access. The following steps are taken
to perform dequeue operation −
1. Step 1 − Check if the queue is empty.
2. Step 2 − If the queue is empty, produce underflow error and exit.
3. Step 3 − If the queue is not empty, access the data where front is pointing.
4. Step 4 − Increment front pointer to point to the next available data element.
5. Step 5 − Return success.

66
67
IMPLEMENTATION OF DEQUEUE

int dequeue()
{
if(isempty())
return 0;
int data = queue[front];
front = front + 1;
}
Return data

68
PEEK()

This function helps to see the data at the front of the queue. The algorithm of peek()
function is as follows −

69
ISFULL()

As we are using single dimension array to implement queue, we just check for the rear
pointer to reach at MAXSIZE to determine that the queue is full. In case we maintain
the queue in a circular linked-list, the algorithm will differ. Algorithm of isfull()
function −

70
ISEMPTY()

If the value of front is less than MIN or 0, it tells that the queue is not yet initialized,
hence empty.

71

You might also like