0% found this document useful (0 votes)
134 views49 pages

What Is Data Structure

A data structure is a way of organizing and storing data in a computer so that it can be accessed efficiently. There are different types of data structures including linear structures like arrays, stacks and queues, and non-linear structures like trees and graphs. Data structures allow us to store, organize, process and access data efficiently. They are essential for arranging data in memory and performing operations on large datasets. Common data structures include arrays, linked lists, stacks, queues, trees and graphs.

Uploaded by

h4nj68z8xx
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)
134 views49 pages

What Is Data Structure

A data structure is a way of organizing and storing data in a computer so that it can be accessed efficiently. There are different types of data structures including linear structures like arrays, stacks and queues, and non-linear structures like trees and graphs. Data structures allow us to store, organize, process and access data efficiently. They are essential for arranging data in memory and performing operations on large datasets. Common data structures include arrays, linked lists, stacks, queues, trees and graphs.

Uploaded by

h4nj68z8xx
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/ 49

What is Data Structure:

A data structure is a storage that is used to store and organize data. It is a way of arranging data on a computer so that it can be
accessed and updated efficiently.
A data structure is not only used for organizing the data. It is also used for processing, retrieving, and storing data. There are
different basic and advanced types of data structures that are used in almost every program or software system that has been
developed. So we must have good knowledge of data structures.

Data structures are an integral part of computers used for the arrangement of data in memory. They are essential and
responsible for organizing, processing, accessing, and storing data efficiently. But this is not all. Various types of data structures
have their own characteristics, features, applications, advantages, and disadvantages. So how do you identify a data structure
that is suitable for a particular task? What is meant by the term ‘Data Structure’? How many types of data structures are there
and what are they used for?

How Data Structure varies from Data Type:


We already have learned about data structure. Many times, what happens is that people get confused between data type and
data structure. So let’s see a few differences between data type and data structure to make it clear.
Data Type Data Structure

The data type is the form of a


Data structure is a collection of different
variable to which a value can be
kinds of data. That entire data can be
assigned. It defines that the
represented using an object and can be
particular variable will assign the
used throughout the program.
values of the given data type only.

It can hold value but not data. It can hold multiple types of data within a
Therefore, it is dataless. single object.

The implementation of a data type is Data structure implementation is known as


known as abstract implementation. concrete implementation.

There is no time complexity in the In data structure objects, time complexity


case of data types. plays an important role.

While in the case of data structures, the


In the case of data types, the value
data and its value acquire the space in the
of data is not stored because it only
computer’s main memory. Also, a data
represents the type of data that can
structure can hold different kinds and types
be stored.
of data within one single object.

Data type examples are int, float, Data structure examples are stack, queue,
double, etc. tree, etc.
Classification of Data Structure:
Data structure has many different uses in our daily life. There are many different data structures that are used to solve different
mathematical and logical problems. By using data structure, one can organize and process a very large amount of data in a
relatively short period. Let’s look at different data structures that are used in different situations.

Classification of Data Structure

 Linear data structure: Data structure in which data elements are arranged sequentially or linearly, where each element is
attached to its previous and next adjacent elements, is called a linear data structure.
Examples of linear data structures are array, stack, queue, linked list, etc.
 Static data structure: Static data structure has a fixed memory size. It is easier to access the elements in a
static data structure.
An example of this data structure is an array.
 Dynamic data structure: In the dynamic data structure, the size is not fixed. It can be randomly updated during
the runtime which may be considered efficient concerning the memory (space) complexity of the code.
Examples of this data structure are queue, stack, etc.
 Non-linear data structure: Data structures where data elements are not placed sequentially or linearly are called non-linear
data structures. In a non-linear data structure, we can’t traverse all the elements in a single run only.
Examples of non-linear data structures are trees and graphs.
Need Of Data structure :
The structure of the data and the synthesis of the algorithm are relative to each other. Data presentation must be easy to
understand so the developer, as well as the user, can make an efficient implementation of the operation.
Data structures provide an easy way of organizing, retrieving, managing, and storing data.
Here is a list of the needs for data.
1. Data structure modification is easy.
2. It requires less time.
3. Save storage memory space.
4. Data representation is easy.
5. Easy access to the large database.

Arrays:
An array is a linear data structure and it is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together in one place. It allows the processing of a large amount of data in a relatively short
period. The first element of the array is indexed by a subscript of 0. There are different operations possible in an array, like
Searching, Sorting, Inserting, Traversing, Reversing, and Deleting.
Array

Characteristics of an Array:
An array has various characteristics which are as follows:
 Arrays use an index-based data structure which helps to identify each of the elements in an array easily using the index.
 If a user wants to store multiple values of the same data type, then the array can be utilized efficiently.
 An array can also handle complex data structures by storing data in a two-dimensional array.
 An array is also used to implement other data structures like Stacks, Queues, Heaps, Hash tables, etc.
 The search process in an array can be done very easily.
Operations performed on array:
 Initialization: An array can be initialized with values at the time of declaration or later using an assignment statement.
 Accessing elements: Elements in an array can be accessed by their index, which starts from 0 and goes up to the size of the
array minus one.
 Searching for elements: Arrays can be searched for a specific element using linear search or binary search algorithms.
 Sorting elements: Elements in an array can be sorted in ascending or descending order using algorithms like bubble sort,
insertion sort, or quick sort.
 Inserting elements: Elements can be inserted into an array at a specific location, but this operation can be time-consuming
because it requires shifting existing elements in the array.
 Deleting elements: Elements can be deleted from an array by shifting the elements that come after it to fill the gap.
 Updating elements: Elements in an array can be updated or modified by assigning a new value to a specific index.
 Traversing elements: The elements in an array can be traversed in order, visiting each element once.
These are some of the most common operations performed on arrays. The specific operations and algorithms used may vary
based on the requirements of the problem and the programming language used.
Applications of Array:
Different applications of an array are as follows:
 An array is used in solving matrix problems.
 Database records are also implemented by an array.
 It helps in implementing a sorting algorithm.
 It is also used to implement other data structures like Stacks, Queues, Heaps, Hash tables, etc.
 An array can be used for CPU scheduling.
 Can be applied as a lookup table in computers.
 Arrays can be used in speech processing where every speech signal is an array.
 The screen of the computer is also displayed by an array. Here we use a multidimensional array.
 The array is used in many management systems like a library, students, parliament, etc.
 The array is used in the online ticket booking system. Contacts on a cell phone are displayed by this array.
 In games like online chess, where the player can store his past moves as well as current moves. It indicates a hint of
position.
 To save images in a specific dimension in the android Like 360*1200
Real-Life Applications of Array:
 An array is frequently used to store data for mathematical computations.
 It is used in image processing.
 It is also used in record management.
 Book pages are also real-life examples of an array.
 It is used in ordering boxes as well.
Want to get started with arrays? You can try out our curated articles and lists for the best practice:
Linked list:
A linked list is a linear data structure in which elements are not stored at contiguous memory locations. The elements in a linked
list are linked using pointers as shown in the below image:
Types of linked lists:
 Singly-linked list
 Doubly linked list
 Circular linked list
 Doubly circular linked list

Linked List

Characteristics of a Linked list:


A linked list has various characteristics which are as follows:
 A linked list uses extra memory to store links.
 During the initialization of the linked list, there is no need to know the size of the elements.
 Linked lists are used to implement stacks, queues, graphs, etc.
 The first node of the linked list is called the Head.
 The next pointer of the last node always points to NULL.
 In a linked list, insertion and deletion are possible easily.
 Each node of the linked list consists of a pointer/link which is the address of the next node.
 Linked lists can shrink or grow at any point in time easily.
Operations performed on Linked list:
A linked list is a linear data structure where each node contains a value and a reference to the next node. Here are some
common operations performed on linked lists:
 Initialization: A linked list can be initialized by creating a head node with a reference to the first node. Each subsequent
node contains a value and a reference to the next node.
 Inserting elements: Elements can be inserted at the head, tail, or at a specific position in the linked list.
 Deleting elements: Elements can be deleted from the linked list by updating the reference of the previous node to point to
the next node, effectively removing the current node from the list.
 Searching for elements: Linked lists can be searched for a specific element by starting from the head node and following
the references to the next nodes until the desired element is found.
 Updating elements: Elements in a linked list can be updated by modifying the value of a specific node.
 Traversing elements: The elements in a linked list can be traversed by starting from the head node and following the
references to the next nodes until the end of the list is reached.
 Reversing a linked list: The linked list can be reversed by updating the references of each node so that they point to the
previous node instead of the next node.
These are some of the most common operations performed on linked lists. The specific operations and algorithms used may
vary based on the requirements of the problem and the programming language used.
Applications of the Linked list:
Different applications of linked lists are as follows:
 Linked lists are used to implement stacks, queues, graphs, etc.
 Linked lists are used to perform arithmetic operations on long integers.
 It is used for the representation of sparse matrices.
 It is used in the linked allocation of files.
 It helps in memory management.
 It is used in the representation of Polynomial Manipulation where each polynomial term represents a node in the linked list.
 Linked lists are used to display image containers. Users can visit past, current, and next images.
 They are used to store the history of the visited page.
 They are used to perform undo operations.
 Linked are used in software development where they indicate the correct syntax of a tag.
 Linked lists are used to display social media feeds.
Real-Life Applications of a Linked list:
 A linked list is used in Round-Robin scheduling to keep track of the turn in multiplayer games.
 It is used in image viewer. The previous and next images are linked, and hence can be accessed by the previous and next
buttons.
 In a music playlist, songs are linked to the previous and next songs.
Want to get started with a linked list? You can try out our curated articles and lists for the best practice:
Stack:
Stack is a linear data structure that follows a particular order in which the operations are performed. The order is LIFO(Last in
first out). Entering and retrieving data is possible from only one end. The entering and retrieving of data is also called push and
pop operation in a stack. There are different operations possible in a stack like reversing a stack using recursion, Sorting,
Deleting the middle element of a stack, etc.

Characteristics of a Stack:
Stack has various different characteristics which are as follows:
 Stack is used in many different algorithms like Tower of Hanoi, tree traversal, recursion, etc.
 Stack is implemented through an array or linked list.
 It follows the Last In First Out operation i.e., an element that is inserted first will pop in last and vice versa.
 The insertion and deletion are performed at one end i.e. from the top of the stack.
 In stack, if the allocated space for the stack is full, and still anyone attempts to add more elements, it will lead to stack
overflow.
Applications of Stack:
Different applications of Stack are as follows:
 The stack data structure is used in the evaluation and conversion of arithmetic expressions.
 Stack is used in Recursion.
 It is used for parenthesis checking.
 While reversing a string, the stack is used as well.
 Stack is used in memory management.
 It is also used for processing function calls.
 The stack is used to convert expressions from infix to postfix.
 The stack is used to perform undo as well as redo operations in word processors.
 The stack is used in virtual machines like JVM.
 The stack is used in the media players. Useful to play the next and previous song.
 The stack is used in recursion operations.

Operation performed on stack ;


A stack is a linear data structure that implements the Last-In-First-Out (LIFO) principle. Here are some common operations
performed on stacks:
 Push: Elements can be pushed onto the top of the stack, adding a new element to the top of the stack.
 Pop: The top element can be removed from the stack by performing a pop operation, effectively removing the last element
that was pushed onto the stack.
 Peek: The top element can be inspected without removing it from the stack using a peek operation.
 IsEmpty: A check can be made to determine if the stack is empty.
 Size: The number of elements in the stack can be determined using a size operation.
These are some of the most common operations performed on stacks. The specific operations and algorithms used may vary
based on the requirements of the problem and the programming language used. Stacks are commonly used in applications such
as evaluating expressions, implementing function call stacks in computer programs, and many others.
Real-Life Applications of Stack:
 Real life example of a stack is the layer of eating plates arranged one above the other. When you remove a plate from the
pile, you can take the plate to the top of the pile. But this is exactly the plate that was added most recently to the pile. If you
want the plate at the bottom of the pile, you must remove all the plates on top of it to reach it.
 Browsers use stack data structures to keep track of previously visited sites.
 Call log in mobile also uses stack data structure.
Want to get started with Stack? You can try out our curated articles and lists for the best practice:
Queue:
Queue is a linear data structure that follows a particular order in which the operations are performed. The order is First In First
Out(FIFO) i.e. the data item stored first will be accessed first. In this, entering and retrieving data is not done from only one end.
An example of a queue is any queue of consumers for a resource where the consumer that came first is served first. Different
operations are performed on a Queue like Reversing a Queue (with or without using recursion), Reversing the first K elements of
a Queue, etc. A few basic operations performed In Queue are enqueue, dequeue, front, rear, etc.

Characteristics of a Queue:
The queue has various different characteristics which are as follows:
 The queue is a FIFO (First In First Out) structure.
 To remove the last element of the Queue, all the elements inserted before the new element in the queue must be removed.
 A queue is an ordered list of elements of similar data types.
Applications of Queue:
Different applications of Queue are as follows:
 Queue is used for handling website traffic.
 It helps to maintain the playlist in media players.
 Queue is used in operating systems for handling interrupts.
 It helps in serving requests on a single shared resource, like a printer, CPU task scheduling, etc.
 It is used in the asynchronous transfer of data e.g. pipes, file IO, and sockets.
 Queues are used for job scheduling in the operating system.
 In social media to upload multiple photos or videos queue is used.
 To send an e-mail queue data structure is used.
 To handle website traffic at a time queues are used.
 In Windows operating system, to switch multiple applications.
Operation performed on queue:
A queue is a linear data structure that implements the First-In-First-Out (FIFO) principle. Here are some common operations
performed on queues:
 Enqueue: Elements can be added to the back of the queue, adding a new element to the end of the queue.
 Dequeue: The front element can be removed from the queue by performing a dequeue operation, effectively removing the
first element that was added to the queue.
 Peek: The front element can be inspected without removing it from the queue using a peek operation.
 IsEmpty: A check can be made to determine if the queue is empty.
 Size: The number of elements in the queue can be determined using a size operation.
These are some of the most common operations performed on queues. The specific operations and algorithms used may vary
based on the requirements of the problem and the programming language used. Queues are commonly used in applications
such as scheduling tasks, managing communication between processes, and many others.
Real-Life Applications of Queue:
 A real-world example of a queue is a single-lane one-way road, where the vehicle that enters first will exit first.
 A more real-world example can be seen in the queue at the ticket windows.
 A cashier line in a store is also an example of a queue.
 People on an escalator
Want to get started with Queue? You can try out our curated articles and lists for the best practice:
Tree:
A tree is a non-linear and hierarchical data structure where the elements are arranged in a tree-like structure. In a tree, the
topmost node is called the root node. Each node contains some data, and data can be of any type. It consists of a central node,
structural nodes, and sub-nodes which are connected via edges. Different tree data structures allow quicker and easier access
to the data as it is a non-linear data structure. A tree has various terminologies like Node, Root, Edge, Height of a tree, Degree
of a tree, etc.
There are different types of Tree-like
 Binary Tree,
 Binary Search Tree,
 AVL Tree,
 B-Tree, etc.

Tree

Characteristics of a Tree:
The tree has various different characteristics which are as follows:
 A tree is also known as a Recursive data structure.
 In a tree, the Height of the root can be defined as the longest path from the root node to the leaf node.
 In a tree, one can also calculate the depth from the top to any node. The root node has a depth of 0.
Applications of Tree:
Different applications of Tree are as follows:
 Heap is a tree data structure that is implemented using arrays and used to implement priority queues.
 B-Tree and B+ Tree are used to implement indexing in databases.
 Syntax Tree helps in scanning, parsing, generation of code, and evaluation of arithmetic expressions in Compiler design.
 K-D Tree is a space partitioning tree used to organize points in K-dimensional space.
 Spanning trees are used in routers in computer networks.
Operation performed on tree:
A tree is a non-linear data structure that consists of nodes connected by edges. Here are some common operations performed
on trees:
 Insertion: New nodes can be added to the tree to create a new branch or to increase the height of the tree.
 Deletion: Nodes can be removed from the tree by updating the references of the parent node to remove the reference to the
current node.
 Search: Elements can be searched for in a tree by starting from the root node and traversing the tree based on the value of
the current node until the desired node is found.
 Traversal: The elements in a tree can be traversed in several different ways, including in-order, pre-order, and post-order
traversal.
 Height: The height of the tree can be determined by counting the number of edges from the root node to the furthest leaf
node.
 Depth: The depth of a node can be determined by counting the number of edges from the root node to the current node.
 Balancing: The tree can be balanced to ensure that the height of the tree is minimized and the distribution of nodes is as
even as possible.
These are some of the most common operations performed on trees. The specific operations and algorithms used may vary
based on the requirements of the problem and the programming language used. Trees are commonly used in applications such
as searching, sorting, and storing hierarchical data.
Real-Life Applications of Tree:
 In real life, tree data structure helps in Game Development.
 It also helps in indexing in databases.
 A Decision Tree is an efficient machine-learning tool, commonly used in decision analysis. It has a flowchart-like structure
that helps to understand data.
 Domain Name Server also uses a tree data structure.
 The most common use case of a tree is any social networking site.
Want to get started with Tree? You can try out our curated articles and lists for the best practice:
Graph:
A graph is a non-linear data structure that consists of vertices (or nodes) and edges. It consists of a finite set of vertices and set
of edges that connect a pair of nodes. The graph is used to solve the most challenging and complex programming problems. It
has different terminologies which are Path, Degree, Adjacent vertices, Connected components, etc.

Graph

Characteristics of Graph:
The graph has various different characteristics which are as follows:
 The maximum distance from a vertex to all the other vertices is considered the Eccentricity of that vertex.
 The vertex having minimum Eccentricity is considered the central point of the graph.
 The minimum value of Eccentricity from all vertices is considered the radius of a connected graph.
Applications of Graph:
Different applications of Graphs are as follows:
 The graph is used to represent the flow of computation.
 It is used in modeling graphs.
 The operating system uses Resource Allocation Graph.
 Also used in the World Wide Web where the web pages represent the nodes.
Operation performed on Graph:
A graph is a non-linear data structure consisting of nodes and edges. Here are some common operations performed on graphs:
 Add Vertex: New vertices can be added to the graph to represent a new node.
 Add Edge: Edges can be added between vertices to represent a relationship between nodes.
 Remove Vertex: Vertices can be removed from the graph by updating the references of adjacent vertices to remove the
reference to the current vertex.
 Remove Edge: Edges can be removed by updating the references of the adjacent vertices to remove the reference to the
current edge.
 Depth-First Search (DFS): A graph can be traversed using a depth-first search by visiting the vertices in a depth-first
manner.
 Breadth-First Search (BFS): A graph can be traversed using a breadth-first search by visiting the vertices in a breadth-first
manner.
 Shortest Path: The shortest path between two vertices can be determined using algorithms such as Dijkstra’s algorithm or
A* algorithm.
 Connected Components: The connected components of a graph can be determined by finding sets of vertices that are
connected to each other but not to any other vertices in the graph.
 Cycle Detection: Cycles in a graph can be detected by checking for back edges during a depth-first search.
These are some of the most common operations performed on graphs. The specific operations and algorithms used may vary
based on the requirements of the problem and the programming language used. Graphs are commonly used in applications
such as computer networks, social networks, and routing problems.
Real-Life Applications of Graph:
 One of the most common real-world examples of a graph is Google Maps where cities are located as vertices and paths
connecting those vertices are located as edges of the graph.
 A social network is also one real-world example of a graph where every person on the network is a node, and all of their
friendships on the network are the edges of the graph.
 A graph is also used to study molecules in physics and chemistry.
Want to get started with Graph? You can try out our curated articles and lists for the best practice:
Advantages of data structure:
1. Improved data organization and storage efficiency.
2. Faster data retrieval and manipulation.
3. Facilitates the design of algorithms for solving complex problems.
4. Eases the task of updating and maintaining the data.
5. Provides a better understanding of the relationships between data elements.

Disadvantage of Data Structure:


1. Increased computational and memory overhead.
2. Difficulty in designing and implementing complex data structures.
3. Limited scalability and flexibility.
4. Complexity in debugging and testing.
5. Difficulty in modifying existing data structures.
C PROGRAMS
1. To Access String
#include<stdio.h>
#include<conio.h>
void main()
{ int a=5;
char name[25];
clrscr();

printf("the value of a is%d",a);


gets(name);
puts(name);
getch();
}
2. Pointers of Pointer
#include<stdio.h>
#include<conio.h>
void g(char **);
void main()
{
char line[5]={'a','b','c','d','e'};
char *p=line;
g(&p);
printf("%c",*p);
getch();
}
void g(char **g2)
{
(*g2)++;
}
3. Passing pointer to function as argument
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{
int m=4,n=5;
clrscr();
swap(&m,&n);
printf("%d %d\n",m,n);
getch();
}
void swap(int *a,int *b)
{
int t;
t=*a;
*a=*b;
*b=t;
}
4. Returning pointer to function
#include<stdio.h>
#include<conio.h>
int *swap(int *,int *);
void main()
{
int m=4,n=5,*p;
clrscr();
p=swap(&m,&n);
printf("%d \n",*p);
getch();
}
int *swap(int *a,int *b)
{
if(*a>*b)
return a;
if(*b>*a)
return b;
}
5. Pointer of function
#include<stdio.h>
#include<conio.h>
intsum(int ,int );
void main()
{
ints,(*f)(int,int);
f=sum;
s=f(10,20);
clrscr();
printf("%d \n",s);
getch();
}
intsum(inta,int b)
{
return a+b;
}
6. Passing Structure to function
#include<stdio.h>
#include<conio.h>
struct car
{ char n[10];
int price;

};
void printc(struct car c)
{ printf("the name is %s\n",c.n);
printf("the prize is %d",c.price);
}
void main()
{
struct car c={"tata", 23};
clrscr();
printc(c);
getch();
}
7. FILE HANDING IN C
a. Create a File in C
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *p;
clrscr();
p=fopen("2.txt","a");
if(p)
printf("file created");
else
printf("not created");
getch();
fclose(p);
}
b. Write character to File
#include<stdio.h>
#include<conio.h>
void main()
{
char c[25]="vaishali";
inti,l=strlen(c);
FILE *fp;
fp=fopen("1.txt","w");
if(fp==NULL)
printf("unable to open");
else
{
for(i=0;i<l;i++)
{
fputc(c[i],fp);
}
}
fclose(fp);
}
c. Write String to File
#include<stdio.h>
#include<conio.h>
void main()
{
char c[25];

FILE *fp;
fp=fopen("1.txt","a");
if(fp==NULL)
printf("unable to open");
else
{ printf("enter string to store ");
scanf("%s",c);
fputs(c,fp);

}
fclose(fp);
}
d. Write formatted string to file
#include<stdio.h>
#include<conio.h>
void main()
{
char c[25]="is good teacher";

FILE *fp;
fp=fopen("1.txt","a");
if(fp==NULL)
printf("unable to open");
else
{ fprintf(fp," %s",c);

}
fclose(fp);
}
e. Read Character from file
#include<stdio.h>
#include<conio.h>
void main()
{
char c;

FILE *fp;
fp=fopen("1.txt","r");
if(fp==NULL)
printf("unable to open");
else
{ while(!feof(fp))
{ c=fgetc(fp);
printf("%c",c);

}
getch();
}
fclose(fp);

}
f. Read String from file
#include<stdio.h>
#include<conio.h>
void main()
{
char c[35];

FILE *fp;
fp=fopen("1.txt","r");
if(fp==NULL)
printf("unable to open");
else
{ while(!feof(fp))
{ fgets(fp,35,c)

}
getch();
}
fclose(fp);

}
g.Write structure to File using fwrite and fread function
#include<stdio.h>
#include<conio.h>
struct c
{
char fname[20];
char lname[20];
}s;
void main()
{
intch,i;
char ch1;
FILE *p;
clrscr();
do{
printf("\n1.Add\n2.Display\n Enter ur
choice");
scanf("%d",&ch);

switch(ch)
{
case 1:
p=fopen("4.txt","a");
printf("enter First name:");
scanf("%s",s.fname);
printf("enter Last name:");
scanf("%s",s.lname);
fwrite(&s,sizeof(s),1,p);
fclose(p);
break;
case 2:
p=fopen("4.txt","r");
while(fread(&s,sizeof(s),1,p))
{

printf("\t%s\t%s\n",s.fname,s.lname);
}
fclose(p);
break;
default:
printf("invalid choice");
break;
}
printf("Do u want to countinue..(Y/N)");
scanf("%c",&ch1);
ch1=getchar();

}while(ch1=='y'||ch1=='Y');

}
RECURSION IN C
Without Recursion
intfact(int a)
{
inti,f=1;
if(a==1)
return f;
else{

for(i=2;i<=a;i++)
{
f=f*i;
}
return f;}

}
Example-1
#include<stdio.h>
#include<conio.h>
int fact(int);
void main()
{
intn,ans;
clrscr();
printf("Enter number:");
scanf("%d",&n);
ans=fact(n);
printf("The factorial of %d is %d",n,ans);
getch();

}
intfact(int a)
{
int f;
if(a==1)
f=1;
else
{
f=a*fact(a-1);
return f;
}
}
/*
Dry run
step -1
check 5==1 no
then
execute else part 5 * 24 = 120
step -2
check 4==1 no
in else part 4 * 6=24
step -3
check 3==1 no
in else part 3 * 2=6
step -4
check 2==1 no
in else part 2 * 1 =2
step-5
return 1
*/
Example-2
#include<stdio.h>
#include<conio.h>
int sum(int);
void main()
{
intr,n=10;
clrscr();
r=sum(n);
printf("%d",r);
getch();

}
intsum(int a)
{
if(a>0)
return a+sum(a-1);
else
return 0;
}
ADT in c
Data types such as int, float, double, long, etc. are
considered to be in-built data types and we can perform basic
operations with them such as addition, subtraction, division,
multiplication, etc. Now there might be a situation when we need
operations for our user-defined data type which have to be
defined. These operations can be defined only as and when we
require them. So, in order to simplify the process of solving
problems, we can create data structures along with their
operations, and such data structures that are not in-built are
known as Abstract Data Type (ADT).
Abstract Data type (ADT) is a type (or class) for
objects whose behavior is defined by a set of values and a set of
operations. The definition of ADT only mentions what operations
are to be performed but not how these operations will be
implemented. It does not specify how data will be organized in
memory and what algorithms will be used for implementing the
operations. It is called “abstract” because it gives an
implementation-independent view.
The process of providing only the essentials and
hiding the details is known as abstraction.
The user of data type does not need to know how that data type is implemented, for example, we have been
using Primitive values like int, float, char data types only with the knowledge that these data type can
operate and be performed on without any idea of how they are implemented.
So a user only needs to know what a data type can do, but not how it will be implemented. Think of ADT as
a black box which hides the inner structure and design of the data type. Now we’ll define three ADTs
namely List ADT, Stack ADT, Queue ADT.
1. List ADT

Vies of list

 The data is generally stored in key sequence in a list which has a head structure consisting
of count, pointers and address of compare function needed to compare the data in the list.
 The data node contains the pointer to a data structure and a self-referential pointer which points to the
next node in the list.
 The List ADT Functions is given below:
 get() – Return an element from the list at any given position.
 insert() – Insert an element at any position of the list.
 remove() – Remove the first occurrence of any element from a non-empty list.
 removeAt() – Remove the element at a specified location from a non-empty list.
 replace() – Replace an element at any position by another element.
 size() – Return the number of elements in the list.
 isEmpty() – Return true if the list is empty, otherwise return false.
 isFull() – Return true if the list is full, otherwise return false.
2. Stack ADT

View of stack

 In Stack ADT Implementation instead of data being stored in each node, the pointer to data is stored.
 The program allocates memory for the data and address is passed to the stack ADT.
 The head node and the data nodes are encapsulated in the ADT. The calling function can only see the
pointer to the stack.
 The stack head structure also contains a pointer to top and count of number of entries currently in stack.
 push() – Insert an element at one end of the stack called top.
 pop() – Remove and return the element at the top of the stack, if it is not empty.
 peek() – Return the element at the top of the stack without removing it, if the stack is not empty.
 size() – Return the number of elements in the stack.
 isEmpty() – Return true if the stack is empty, otherwise return false.
 isFull() – Return true if the stack is full, otherwise return false.
3. Queue ADT

View of Queue

 The queue abstract data type (ADT) follows the basic design of the stack abstract data type.
 Each node contains a void pointer to the data and the link pointer to the next element in the queue. The
program’s responsibility is to allocate memory for storing the data.
 enqueue() – Insert an element at the end of the queue.
 dequeue() – Remove and return the first element of the queue, if the queue is not empty.
 peek() – Return the element of the queue without removing it, if the queue is not empty.
 size() – Return the number of elements in the queue.
 isEmpty() – Return true if the queue is empty, otherwise return false.
 isFull() – Return true if the queue is full, otherwise return false.

Features of ADT:
Abstract data types (ADTs) are a way of encapsulating data and operations on that data into a single
unit. Some of the key features of ADTs include:
 Abstraction: The user does not need to know the implementation of the data structure only essentials
are provided.
 Better Conceptualization: ADT gives us a better conceptualization of the real world.
 Robust: The program is robust and has the ability to catch errors.
 Encapsulation: ADTs hide the internal details of the data and provide a public interface for users to
interact with the data. This allows for easier maintenance and modification of the data structure.
 Data Abstraction: ADTs provide a level of abstraction from the implementation details of the data. Users
only need to know the operations that can be performed on the data, not how those operations are
implemented.
 Data Structure Independence: ADTs can be implemented using different data structures, such as arrays
or linked lists, without affecting the functionality of the ADT.
 Information Hiding: ADTs can protect the integrity of the data by allowing access only to authorized
users and operations. This helps prevent errors and misuse of the data.
 Modularity: ADTs can be combined with other ADTs to form larger, more complex data structures. This
allows for greater flexibility and modularity in programming.
Overall, ADTs provide a powerful tool for organizing and manipulating data in a structured and efficient
manner.
Abstract data types (ADTs) have several advantages and disadvantages that should be considered when
deciding to use them in software development. Here are some of the main advantages and disadvantages of
using ADTs:

Advantages:

 Encapsulation: ADTs provide a way to encapsulate data and operations into a single unit, making it
easier to manage and modify the data structure.
 Abstraction: ADTs allow users to work with data structures without having to know the implementation
details, which can simplify programming and reduce errors.
 Data Structure Independence: ADTs can be implemented using different data structures, which can
make it easier to adapt to changing needs and requirements.
 Information Hiding: ADTs can protect the integrity of data by controlling access and preventing
unauthorized modifications.
 Modularity: ADTs can be combined with other ADTs to form more complex data structures, which can
increase flexibility and modularity in programming.

Disadvantages:

 Overhead: Implementing ADTs can add overhead in terms of memory and processing, which can affect
performance.
 Complexity: ADTs can be complex to implement, especially for large and complex data structures.
 Learning Curve: Using ADTs requires knowledge of their implementation and usage, which can take time
and effort to learn.
 Limited Flexibility: Some ADTs may be limited in their functionality or may not be suitable for all types of
data structures.
 Cost: Implementing ADTs may require additional resources and investment, which can increase the cost
of development.
Overall, the advantages of ADTs often outweigh the disadvantages, and they are widely used in software
development to manage and manipulate data in a structured and efficient way. However, it is important to
consider the specific needs and requirements of a project when deciding whether to use ADTs.
From these definitions, we can clearly see that the definitions do not specify how these ADTs will be
represented and how the operations will be carried out. There can be different ways to implement an ADT,
for example, the List ADT can be implemented using arrays, or singly linked list or doubly linked list.
Similarly, stack ADT and Queue ADT can be implemented using arrays or linked lists.
Unit -2

The Ordered List Abstract Data Type


We will now consider a type of list known as an ordered list. For example, if the list of integers shown above were an ordered list (ascending
order), then it could be written as 17, 26, 31, 54, 77, and 93. Since 17 is the smallest item, it occupies the first position in the list. Likewise,
since 93 is the largest, it occupies the last position.
The structure of an ordered list is a collection of items where each item holds a relative position that is based upon some underlying
characteristic of the item. The ordering is typically either ascending or descending and we assume that list items have a meaningful
comparison operation that is already defined. Many of the ordered list operations are the same as those of the unordered list .

 OrderedList() creates a new ordered list that is empty. It needs no parameters and returns an empty list.
 add(item) adds a new item to the list making sure that the order is preserved. It needs the item and returns nothing. Assume the item i s not
already in the list.
 remove(item) removes the item from the list. It needs the item and modifies the list. Assume the item is present in the list.
 search(item) searches for the item in the list. It needs the item and returns a boolean value.
 isEmpty() tests to see whether the list is empty. It needs no parameters and returns a boolean value.
 size() returns the number of items in the list. It needs no parameters and returns an integer.
 index(item) returns the position of item in the list. It needs the item and returns the index. Assume the item is in the list.
 pop() removes and returns the last item in the list. It needs nothing and returns an item. Assume the list has at least one item.
 pop(pos) removes and returns the item at position pos. It needs the position and returns the item. Assume the item is in the list.

List Data Structure


The list can be defined as an abstract data type in which the elements are stored in an ordered manner for easier and
efficient retrieval of the elements. List Data Structure allows repetition that means a single piece of data can occur
more than once in a list. In the case of multiple entries of the same data, each entry of that repeating data is
considered as a distinct item or entry. It is very much similar to the array but the major difference between the array
and the list data structure is that array stores only homogenous data in them whereas the list (in some programming
languages) can store heterogeneous data items in its object. List Data Structure is also known as a sequence.

The list can be called Dynamic size arrays, which means their size increased as we go on adding data in them and we
need not to pre-define a static size for the list.

For example,

5.8M
760
OOPs Concepts in Java

numbers = [ 1, 2, 3, 4, 5]

In this example, 'numbers' is the name of the List Data Structure object and it has five items stored in it. In the object
named numbers, we have stored all the elements of numeric type. In the list, the indexing starts from zero, which
means if we want to access or retrieve the first element of this list then we need to use index zero and similarly
whenever we want to access any element from this list named numbers. In other words, we can say that element 1 is
on the index 0 and element 2 is on index 1 and similarly for further all elements.

Mixed_data = [205, 'Nirnay', 8.56]

In this second example, mixed_data is the name of the list object that stores the data of different types. In the
mixed_data list, we have stored data of three types, first one is the integer type which is id '205', after the integer data
we have stored a string type data having the value 'Nirnay' stored at index 1 and at last the index value 2, we have
stored a float type data having the value '8.56'.

To access the elements of the mixed_data list, we need to follow the same approach as defined in the previous
example.

And we can add more data to these defined List objects and that will get appended at the last of the list. For example,
if we add another data in the mixed_data list, it will get appended after the float value object having value '8.56'. And
we can add repeating values to these list-objects.

Various operations on the List Data Structure:

The various operations that are performed on a List Data Structure or Sequence are:

o Add or Insert Operation: In the Add or Insert operation, a new item (of any data type) is added in the List
Data Structure or Sequence object.
o Replace or reassign Operation: In the Replace or reassign operation, the already existing value in the List
object is changed or modified. In other words, a new value is added at that particular index of the already
existing value.
o Delete or remove Operation: In the Delete or remove operation, the already present element is deleted or
removed from the Dictionary or associative array object.
o Find or Lookup or Search Operation: In the Find or Lookup operation, the element stored in that List Data
Structure or Sequence object is fetched.
ADDRESS CALCULATION FOR ARRAYS
In computing, row-major order and columnmajor
order describe methods for arranging
multidimensional arrays in linear storage
such as memory.
In row-major order, consecutive elements
of the rows of the array are in contiguous
memory; in column-major order,
consecutive elements of the columns are contiguous.
ROW MAJOR ORDER
The Location of element A[i, j] can be obtained by
evaluating expression:
LOC (A [i, j]) = Base_Address + W [M (i) + (j)]
Base_Address is the address of frst element in the array.
W is the word size. bytes occupied by each element.
N is number of rows in array.
M is number of columns in array.
Base_Address = 2000, W= 2, M=4, N=2, i=1, j=2
LOC (A [i, j])=Base_Address + W [M (i) + (j)]
LOC (A[1, 2])=2000 + 2 *[4*(1) + 2]
=2000 + 2 * [4 + 2]
=2000 + 2 * 6
=2000 + 12
=2012

COLUMN MAJOR
The Location of element A[i, j] can be obtained by evaluating expression:
LOC (A [i, j]) = Base_Address + W [N (j) + (i)]
Base_Address is the address of first element in the array.
W is the word size. bytes occupied by each element.
N is number of rows in array.
M is number of columns in array.
Suppose we want to calculate the address of element A [1, 2].
Base_Address = 2000, W= 2, M=4, N=2, i=1, j=2
LOC (A [i, j])=Base_Address + W [N (j) + (i)]
LOC (A[1, 2])=2000 + 2 *[2*(2) + 1]
=2000 + 2 * [4 + 1]
=2000 + 2 * 5
=2000 + 10
=2010

Sparse Matrix and its representations (Using


Arrays )

A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values. If most of
the elements of the matrix have 0 value, then it is called a sparse matrix.
Why to use Sparse Matrix instead of simple matrix ?
 Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those
elements.
 Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero
elements..
Example:
0 0 3 0 4
0 0 5 7 0
0 0 0 0 0
0 2 6 0 0
Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in
most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means
storing non-zero elements with triples- (Row, Column, value).
Sparse Matrix Representations can be done in many ways following are two common representations:
1. Array representation
2. Linked list representation
Method 1: Using Arrays:
2D array is used to represent a sparse matrix in which there are three rows named as
 Row: Index of row, where non-zero element is located
 Column: Index of column, where non-zero element is located
 Value: Value of the non zero element located at index – (row,column)

intmain()
{
// Assume 4x5 sparse matrix
intsparseMatrix[4][5] =
{
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};

intsize = 0;
for(inti = 0; i< 4; i++)
for(intj = 0; j < 5; j++)
if(sparseMatrix[i][j] != 0)
size++;

// number of columns in compactMatrix (size)


must be
// equal to number of non - zero elements in
// sparseMatrix
intcompactMatrix[3][size];

// Making of new matrix


intk = 0;
for(inti = 0; i< 4; i++)
for(intj = 0; j < 5; j++)
if(sparseMatrix[i][j] != 0)
{
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] =
sparseMatrix[i][j];
k++;
}

for(inti=0; i<3; i++)


{
for(intj=0; j<size; j++)
printf("%d ", compactMatrix[i][j]);

printf("\n");
}
return0;
}

Output
0 0 1 1 3 3
2 4 2 3 1 2
3 4 5 7 2 6
Operation on matrix
Given two sparse matrices (perform operations such as add, multiply or transpose of the matrices in their
sparse form itself. The result should consist of three sparse matrices, one obtained by adding the two input
matrices, one by multiplying the two matrices and one obtained by transpose of the first matrix.

Example: Note that other entries of matrices will be zero as matrices are sparse.
Input :

Matrix 1: (4x4)
Row Column Value
1 2 10
1 4 12
3 3 5
4 1 15
4 2 12

Matrix 2: (4X4)
Row Column Value
1 3 8
2 4 23
3 3 9
4 1 20
4 2 25

Output :

Result of Addition: (4x4)


Row Column Value
1 2 10
1 3 8
1 4 12
2 4 23
3 3 14
4 1 35
4 2 37
Result of Multiplication: (4x4)
Row Column Value
1 1 240
1 2 300
1 4 230
3 3 45
4 3 120
4 4 276

Result of transpose on the first matrix: (4x4)


Row Column Value
1 4 15
2 1 10
2 4 12
3 3 5
4 1 12
The sparse matrix used anywhere in the program is sorted according to its row values. Two elements with
the same row values are further sorted according to their column values.
Now to Add the matrices, we simply traverse through both matrices element by element and insert the
smaller element (one with smaller row and col value) into the resultant matrix. If we come across an element
with the same row and column value, we simply add their values and insert the added data into the resultant
matrix.
To Transpose a matrix, we can simply change every column value to the row value and vice-versa,
however, in this case, the resultant matrix won’t be sorted as we require. Hence, we initially determine the
number of elements less than the current element’s column being inserted in order to get the exact index of
the resultant matrix where the current element should be placed. This is done by maintaining an array index[]
whose ith value indicates the number of elements in the matrix less than the column i.
To Multiply the matrices, we first calculate transpose of the second matrix to simplify our comparisons and
maintain the sorted order. So, the resultant matrix is obtained by traversing through the entire length of both
matrices and summing the appropriate multiplied values.
Any row value equal to x in the first matrix and row value equal to y in the second matrix (transposed one)
will contribute towards result[x][y]. This is obtained by multiplying all such elements having col value in both
matrices and adding only those with the row as x in first matrix and row as y in the second transposed matrix
to get the result[x][y].
For example: Consider 2 matrices:
Row Col Val Row Col Val
1 2 10 1 1 2
1 3 12 1 2 5
2 1 1 2 2 1
2 3 2 3 1 8
The resulting matrix after multiplication will be obtained as follows:
Transpose of second matrix:

Row Col Val Row Col Val


1 2 10 1 1 2
1 3 12 1 3 8
2 1 1 2 1 5
2 3 2 2 2 1

Summation of multiplied values:

result[1][1] = A[1][3]*B[1][3] = 12*8 = 96


result[1][2] = A[1][2]*B[2][2] = 10*1 = 10
result[2][1] = A[2][1]*B[1][1] + A[2][3]*B[1][3] = 2*1 + 2*8 = 18
result[2][2] = A[2][1]*B[2][1] = 1*5 = 5

Any other element cannot be obtained


by any combination of row in
Matrix A and Row in Matrix B.

Hence the final resultant matrix will be:

Row Col Val


1 1 96
1 2 10
2 1 18
2 2 5
Sparse Matrix Multiplication
Algorithm:
- First we have to generate transpose of the second matrix.
- Traverse both the matrices A and sorted B’ row wise while traversing
 Compare 1st column of each row of A to the same of B
 Say A[x][1] matches B[y][1]
 Then store (x,y;A[x][2] * B[y][2]) in resultant matrix
 If multiple rows exist in the resulting matrix with values in the 0th and
1st col.
- Add the 2th column corresponding to the entries and store them
as single row in the matrix.
- Sort the matrix

A B
R C V R C V

1 2 10 These are the 1 1 2


matrices for
1 3 12 Multiplication. 1 2 5

2 1 1 2 2 1

2 3 2 3 1 8
Step 1:
First we have to generate transpose of second matrix i.e. B

B Transpose of B
R C V R C V

1 1 2 These are the 1 1 2


matrices for
1 2 5 Multiplication. 1 3 8

2 2 1 2 1 5

3 1 8 2 2 1

Now 1st column of each row of A to the same of B


Step 1: check A’s first column of first row is in B and if we found then
We have to take A’s row value and B’s rows value and multiply value of
both A and B and insert into final answer matrix.
In this we have A(1,2,10) and that column is match with B(2,2,1) so now we
have to insert 1,2,and 10*1 in to final matrix.
A Transpose of B Final Answer
R C V R C V R C V

1 2 10 1 1 2 1 2 10

1 3 12 1 3 8

2 1 1 2 1 5

2 3 2 2 2 1
Step 2: check A’s first column of first row is in B and if we found then
We have to take A’s row value and B’s rows value and multiply value of
both A and B and insert into final answer matrix.
In this we have A(1,3,12) and that column is match with B(1,3,8) so now we
have to insert 1,1,and 12*8 in to final matrix.
A Transpose of B Final Answer
R C V R C V R C V

1 2 10 1 1 2 1 2 10

1 3 12 1 3 8 1 1 96

2 1 1 2 1 5

2 3 2 2 2 1
Step 3: check A’s first column of first row is in B and if we found then
We have to take A’s row value and B’s column value and multiply value of
both A and B and insert into final answer matrix.
In this we have A (2,1,1) and that column is match with B (1,1,2) so now we
have to insert 2,1, and 1*2 in to final matrix.
A Transpose of B Final Answer
R C V R C V R C V

1 2 10 . 1 1 2 1 2 10

1 3 12 1 3 8 1 3 96

2 1 1 2 1 5 2 1 2

2 3 2 2 2 1
Step 4: check A’s first column of first row is in B and if we found then
We have to take A’s row value and B’s column value and multiply value of
both A and B and insert into final answer matrix.
In this we have A (2,3,2) and that column is match with B (1,1,2) so now we
have to insert 2,1, and 1*2 in to final matrix.
A Transpose of B Final Answer
R C V R C V R C V

1 2 10 . 1 1 2 1 2 10

1 3 12 1 3 8 1 3 96

2 1 1 2 1 5 2 1 2

2 3 2 2 2 1 2 1 16
Step 5:
If we got two row and column values same in two or more row into the final
answer then we add elements values and merge it in one row
A Transpose of B Final Answer
R C V R C V R C V

1 2 10 . 1 1 2 1 2 10

1 3 12 1 3 8 1 3 96

2 1 1 2 1 5 2 1 18

2 3 2 2 2 1
Step 5:
If we got two row and column values same in two or more row into the final
answer then we add elements values and merge it in one row
A Transpose of B Final Answer
R C V R C V R C V

1 2 10 . 1 1 2 1 2 10

1 3 12 1 3 8 1 3 96

2 1 1 2 1 5 2 1 18

2 3 2 2 2 1 2 2 5
Sparse Matrix Addition
We have a two sparse matrices,

A B
1 2 3 4 5 6 1 2 3 4 5 6
1 0 0 0 0 3 0 1 2 0 0 0 0 0
2 0 0 9 0 4 0 2 0 0 18 0 0 0
3 0 8 0 0 0 7 3 0 3 0 24 0 17
4 2 0 0 0 0 0 4 0 0 0 0 0 0
5 0 0 0 0 0 0 5 0 0 0 6 0 0

Step 1: First Find the Non-Zero Element in Both A and B.4


For A matrix: we have 6 non zero elements (2,8,9,3,4,7)

0 1 2 3 4 5 6

5(Row) 1 2 2 3 3 4

6(Col) 5 3 5 2 6 1

6(Non- 3 9 4 8 7 2
Zero)
For B matrix: we have 6 non zero elements (2,18,3,24,17,6)

0 1 2 3 4 5 6

5(Row) 1 2 3 3 3 5

6(Col) 1 3 2 4 6 4

6(Non- 2 18 3 24 17 6
Zero)

Steps for Addition of Sparse Matrix:


Step 1:
First create a same matrix for addition. For this we have to find size of the
new matrix so A has 6 columns and B has 6 columns.
Total size of new matrix is: 6 + 6 = 12
but if we have some common row and column in both A and B matrix so we
have to ignore that column and do not add that column in new matrix.
Common Columns in both A and B
A B
0 1 2 3 4 5 6 0 1 2 3 4 5 6
R 1 2 2 3 3 4 R 1 2 3 3 3 5
C 5 3 5 2 6 1 C 1 3 2 4 6 4
NZ 3 9 4 8 7 2 NZ 2 18 3 24 17 6

There are 3 Row and Column are same in A and B matrix so ignore this 3
so now we have 12-3 = 9 column for new matrix.

C
0 1 2 3 4 5 6 7 8 9

5(Row)
6(Col)

Now start addition Put I and J variable for A and B.


After putting I and J
Algorithm says that first check row’s number of both A and B Matrix.
If both are same then check for columns of both A and B matrix.
If columns of B are less than columns of A, then increase j and add B’s
data to C
If rows of A are less then rows of B, then increase I and add A’s data to C.
If rows and columns are same for the A and B then add element of both A
and B, increment I and J both and then add it into C.
Step-1 In first step row value of both A and B are same then we check for
its column i.e. 5 and 1 so here B’s column values are < A’ column values
so we have to increase j and insert B’s data into the column.

A B
I J
0 1 2 3 4 5 6 0 1 2 3 4 5 6
R 1 2 2 3 3 4 R 1 2 3 3 3 5
C 5 3 5 2 6 1 C 1 3 2 4 6 4
NZ 3 9 4 8 7 2 NZ 2 18 3 24 17 6
After inserting B’s Data into C
0 1 2 3 4 5 6 7 8 9

5(Row) 1

6(Col) 1

2
Step-2row value of A < row value of B so increase I and insert data of A
into the C.
A B
I J
0 1 2 3 4 5 6 0 1 2 3 4 5 6
R 1 2 2 3 3 4 R 1 2 3 3 3 5
C 5 3 5 2 6 1 C 1 3 2 4 6 4
NZ 3 9 4 8 7 2 NZ 2 18 3 24 17 6

After inserting B’s Data into C


0 1 2 3 4 5 6 7 8 9

5(Row) 1 1

6(Col) 1 5

2 3
Step-3row value of A = row value of B and column value of A is also same
of column value of B. now according to an algorithm we have to add
element and insert it into the C.increment I and J both
A B
I J
0 1 2 3 4 5 6 0 1 2 3 4 5 6
R 1 2 2 3 3 4 R 1 2 3 3 3 5
C 5 3 5 2 6 1 C 1 3 2 4 6 4
NZ 3 9 4 8 7 2 NZ 2 18 3 24 17 6
After inserting B’s Data into C
0 1 2 3 4 5 6 7 8 9

5(Row) 1 1 2

6(Col) 1 5 3

2 3 27
Step-4 row value of A < row value of B then increases I and insert A’s data
into C.
A B
I J
0 1 2 3 4 5 6 0 1 2 3 4 5 6
R 1 2 2 3 3 4 R 1 2 3 3 3 5
C 5 3 5 2 6 1 C 1 3 2 4 6 4
NZ 3 9 4 8 7 2 NZ 2 18 3 24 17 6
After inserting B’s Data into C
0 1 2 3 4 5 6 7 8 9

5(Row) 1 1 2 2

6(Col) 1 5 3 5

2 3 27 4

Step-5row of A = row of B and column of A = column of B then add


elements and insert into C. increase both I and j
A B
I J
0 1 2 3 4 5 6 0 1 2 3 4 5 6
R 1 2 2 3 3 4 R 1 2 3 3 3 5
C 5 3 5 2 6 1 C 1 3 2 4 6 4
NZ 3 9 4 8 7 2 NZ 2 18 3 24 17 6
After inserting B’s Data into C
0 1 2 3 4 5 6 7 8 9

5(Row) 1 1 2 2 3

6(Col) 1 5 3 5 2

2 3 27 4 11

Step-6row of A = row of B and column of B< column of A then increase j


and insert it into C
A B
I J
0 1 2 3 4 5 6 0 1 2 3 4 5 6
R 1 2 2 3 3 4 R 1 2 3 3 3 5
C 5 3 5 2 6 1 C 1 3 2 4 6 4
NZ 3 9 4 8 7 2 NZ 2 18 3 24 17 6
After inserting B’s Data into C
0 1 2 3 4 5 6 7 8 9

5(Row) 1 1 2 2 3 3

6(Col) 1 5 3 5 2 4

2 3 27 4 11 24
Step-8row of A < row of B insert data into C
A B
I J
0 1 2 3 4 5 6 0 1 2 3 4 5 6
R 1 2 2 3 3 4 R 1 2 3 3 3 5
C 5 3 5 2 6 1 C 1 3 2 4 6 4
NZ 3 9 4 8 7 2 NZ 2 18 3 24 17 6
After inserting B’s Data into C
0 1 2 3 4 5 6 7 8 9

5(Row) 1 1 2 2 3 3 3 4 5

6(Col) 1 5 3 5 2 4 6 1 4

2 3 27 4 11 24 24 2 6

You might also like