PDSA Manual
PDSA Manual
Lab Manual
Competitive programming lab -Java
Subject :-
Signature
Experiment No. Date of Performance :-
Title :-Write Code and Understand the Concept Variable, data type and Data
Object.
OBJECTIVE- Write Code and Understand the Concept Variable, data type and Data
Object. SOFTWARE REQUIREMENT:-Turbo C/C++ Compiler
HARDWAREREQUIREMENT:- Windows OS, Minimum 8 GB RAM…etc
THEORY-
VARIABLES –
A variable is a name of the memory location. It is used to store data. Its value can be
changed, and it can be reused many times.It is a way to represent memory location through
symbol so that it can be easily identified.
Let's see the syntax to declare a variable:
type variable_list;
Types of Variables –
a) Local Variable- A variable that is declared inside the function or block is called a local
variable.
b) Global Variable-A variable that is declared outside the function or block is called a global
variable. Anyfunction can change the value of the global variable. It is available to all the
functions.
c) Static Variable –A variable that is declared with the static keyword is called static
variable.It retains its value between multiple function calls.
d) Automatic Variable- All variables in C that are declared inside the block, are automatic
variables by default. We can explicitly declare an automatic variable using auto
keyword.
DATA TYPES–
A data type specifies the type of data that a variable can store such as integer, floating,
character, etc.There are the following data types in C language.
1) Int- Integers are entire numbers without any fractional or decimal parts, and the int data
type is used to represent them.It is frequently applied to variables that include values, such
as counts, indices, or other numerical numbers. The int data type may represent
both positive and negative numbers because it is signed by default.An int takes up 2
bytes of memory on most devices, allowing it to store values between around -2 billion and
+2 billion.
2) Char- Individual characters are represented by the char data type. Typically used to
hold ASCII or UTF-8 encoding scheme characters, such as letters, numbers, symbols, or commas.
There are 256 characters that can be represented by a single char, which takes up one byte of
memory. Characters such as 'A', 'b', '5', or '$' are enclosed in single quotes.
3) Float-To represent integers, use the floating data type. Floating numbers can be used to represent
fractional units or numbers with decimal places.The float type is usually used for variables that
require very good precision but may not be very precise. It can store values with an accuracy of
about 6 decimal places and a range of about 3.4 x 1038 in 4 bytes of memory.
1) int age = 25;
2) char grade = 'A';
3) float temperature = 98.6;
1) Array-An array, a derived data type, lets you store a sequence of fixed-size elements of
the same type. It provides a mechanism for joining multiple targets of the same data
under the same name.The index is used to access the elements of the array, with a 0 index for
the first entry. The size of the array is fixed at declaration time and cannot be changed during
program execution. The array components are placed in adjacent memory regions.
2) Pointer-A pointer is a derived data type that keeps track of another data type's memory
address. When a pointer is declared, the data type it refers to is stated first, and then
the variable name is preceded by an asterisk (*).You can have incorrect access and change
the value of variable using pointers by specifying the memory address of the
variable. Pointers are commonly used in tasks such as function pointers, data structures,
and dynamic memory allocation.
3) Structure-A structure is a derived data type that enables the creation of composite data types by
allowing the grouping of many data types under a single name. It gives you the ability to create your
own unique data structures by fusing together variables of various sorts.
1. A structure's members or fields are used to refer to each variable within it.
2. Any data type, including different structures, can be a member of a structure.
3. A structure's members can be accessed by using the dot (.) operator.
4) Union- A derived data type called a union enables you to store various data types in the
same memory address. In contrast to structures, where each member has a separate memory
space, members of a union all share a single memory space. When you need to represent
many data types interchangeably, unions come in handy. Like structures, you can access the
members of a union by using the dot (.) operator.
DATA OBJECT -
The data object is actually a location or region of storage that contains a collection of
attributes or groups of values that act as an aspect, characteristic, quality, or descriptor of
the object. A vehicle is a data object which can be defined or described with the help of a
set of attributes or data.A data object is a collection of one or more data points that create
meaning as a whole. In other words, “data object” is an alternate way of saying “this group of
data should be thought of as standalone.”
The most common example of a data object is a data table, but others include arrays,
pointers, records, files, sets, and scalar types.Values in a data object may have their own
unique IDs, data types, and attributes. In this way, data objects vary across database
structures and different programming languages.An easy way to think about the term “data
object” is that it reflects the simple need for compartmentalizing information in a database
that otherwise looks big and confusing.In addition to compartmentalizing, data analysts use
unique IDs, data types, and attributes to make data even easier to understand. These data
objects are almost always represented in data models, which show relationships between data
objects.
As a list, data objects consist of-
a) Values- The data itself.
b) Unique IDs- One data point that identifies others related to it.
c) Attributes- Additional data within one Unique ID.
d) Data types- Classifications of data such as text, numeric, and boolean.
ALGORITHM OF PROGRAM-
1. Start
2. Declare the variable num, ch, f
3. Print the massage and get the Value of character from User and stored it
in variable ‘ch’.
4. Print the massage and get the Value of Interger from User and stored it
in variable ‘num’.
5. Print the massage and get the Value of Float Number from User and stored it
in variable ‘f’.
6. Print All the Values Accept From User
7. End
C PROGRAM-
scanf(“%d”, &f);
return 0;
}
OUTPUT OF PROGRAM:
CONCLUSION:
Subject :-
Signature
Experiment No. Date of Performance :-
Title :- Write Code and Understand the Concept Constructor and Relationship
INTRODUCTION OF CONSTRUCTOR -
It is a special method that is invoked automatically at the time of object creation. It is used
to initialize the data members of new objects generally. The constructor in C++ has the
same name as the class or structure. It constructs the values i.e. provides data for the object
which is why it is known as constructor.
Constructor is a member function of a class, whose name is same as the class name.
Constructor is a special type of member function that is used to initialize the data members
for an object of a class automatically, when an object of the same class is created.
Constructor is invoked at the time of object creation. It constructs the values i.e. provides
data for the object that is why it is known as constructor. Constructor do not return value,
hence they do not have a return type.
Constructor can be defined inside the class declaration or outside the class declaration
a) Syntax for defining the constructor within the class
<class-name>(list-of-parameters)
{
//constructor definition
}
b) Syntax for defining the constructor outside the class
<class-name>::<class-name>(list-of-parameters)
{
//constructor definition
}
CHARACTERISTICS OF CONSTRUCTOR:-
TYPES OF CONSTRUCTORS :-
1) Default Constructor
Unlike default constructors which do not take any parameters, it is however possible to pass
one or more arguments to a constructor. Constructors that can take arguments are known as
parameterized constructors.
The syntax for declaring parameterized constructor inside the set:
class class_name
{
public:
class_name(variables) //Parameterized constructor declared.
{
…….
}
};
3) Copy Constructor
The copy constructor in c++ is a constructor that creates an object by initialising it with a
previously created object of the same class.
4) Constructor Overloading
In some programs, a class had only one constructor which was either zeroes, one, or more
parameters. The constructor is key for object initialization. The mechanism of the constructor
is made considerably more powerful by uniting with the feature of overloading. It is made
possible by providing more than one constructor in a class called Constructor overloading.
ALGORITHM OF PROGRAM:-
C PROGRAM:-
int main()
{
printf("ID = %d\nName = %s\n", str1 ->empid,str1 -> name);
return 0;
}
OUTPUT OF PROGRAM-
ID = 202324
Name = Robert William
CONCLUSION:
Subject :-
Signature
Experiment No. Date of Performance :-
Title :- Write Code and Understand the Concept List In Data Structure.
THEORY:-
WHAT IS A LIST IN DS?
List is an ordered data structure that is used to store different or same elements in a sequential
manner.A List Data Structure is a distinct set of ordered elements in which the same value can
occur more than once. It is prominently characterized by its flexibility, enabling each element
to be individually accessed and edited depending on the provided position or index. In
many programming languages like Python, this data structure is commonly known as an array.
Defining the List Data Structure -
In computer science, list data structures are invaluable and are utilized to a significant extent
across various applications. They are particularly effective where data has a specific order,
and elements need to be added or removed frequently. For instance, list data structures are
widely used in:
Definition-A Linked List data structure is a linear data structure where each element, referred
to as a node, stores its own data and a reference or link to the next element in the sequence.
Unlike an array or list data structures, elements in linked lists are not stored in consecutive
locations, offering you more flexibility in terms of memory management. Here's a quick
breakdown of the component structure of a linked list:
Node: Every node has two parts - data and a reference to the next node.
Data: This part holds the information. The data stored in a node could be a character, a
string, a number, or a reference to another complex data structure.
Link: This is the reference to the next node. When a link refers to NULL, it marks the
end of the linked list.
Linked lists, as a data structure, come with their own set of benefits that enhance their
usability in numerous applications.
Dynamic Size: The size of arrays and list data structures is fixed, needing the size to
be known ahead of time.
Efficient Operations: Insertions, deletions and adding new data can be done more
efficiently when compared to an array or list as extensive shifting of elements is not
necessary.
Implementation of Other Data Structures: Linked Lists can be used to implement
other complex data structures like Stack, Queue, and Hash Tables.
ALGORITHM OF PROGRAM -
1. START
2. Create a node to store the data
3. Check if the list is empty
4. If the list is empty, add the data to the node and assign the head pointer to it.
5. If the list is not empty, add the data to a node and link to the current head. Assign
the head to the newly added node.
6. END
C PROGRAM -
// Creating a node
DEPT OF E&C ENGG.
K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON
struct node {
int value;
struct node *next;
};
// print the linked list value
void printLinkedlist(struct node *p) {
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}
int main()
{
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three =
NULL; struct node *four =
NULL; struct node *five =
NULL;
// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
four = malloc(sizeof(struct node));
five = malloc(sizeof(struct node));
// Connect nodes
one->next = two;
two->next = three;
three->next = four;
four->next = five;
five->next =
NULL;
DEPT OF E&C ENGG.
K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON
// printing node-value
head = one;
printLinkedlist(head);
}
OUTPUT OF PROGRAM- 45 72 93 21 56
CONCLUSION:
Subject :-
Signature
Experiment No. Date of Performance :-
Title :- Write Code and Understand the Concept Queue in Data Structure
THEORY:
be inserted at that index. On dequeue operation, we will store the value at the front
index and move the front ahead and then return the stored value.
Let’s see the array implementation of the queue data structure using the C
programming language.
ALGORITHM OF PROGRAM
1) Start
2) Ask the user for the operation like insert, delete, display and exit.
According to the option entered, access its respective function using switch statement.
3) Use the variables front and rear to represent the first and last element of the queue.
4) In the function insert(), firstly check if the queue is full. If it is, then print the output
as “Queue Overflow”. Otherwise take the number to be inserted as input and store it
in the variableadd_item. Copy the variable add_item to the array queue_array[] and
increment the variable rear by 1.
5) In the function delete(), firstly check if the queue is empty. If it is, then print the
output as “Queue Underflow”. Otherwise print the first element of the array
queue_array[] and decrement the variable front by 1.
6) In the function display(), using for loop print all the elements of the array starting from
front to rear.
7) Exit.
C PROGRAM-
void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("-*--Queue Operations--*- \n");
printf("1.Insert / Enqueue \n");
printf("2.Delete / Dequeue \n");
printf("3.Display \n");
printf("4.Quit \n\n");
printf("Enter your choice from above List: ");
scanf("%d", &choice);
switch (choice)
{
case 1:insert();break;
case 2:delete();break;
case 3:display();break;
case 4:exit(1);
default:printf("Wrong choice \n");
} // End of switch
} // End of while
} //End of main()
void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty
*/ front = 0;
printf("Enter the Number to Inset the element in queue :
"); scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} // End of insert()
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue Elements is :- ");
for (i = front; i<= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}
Output of Program-
-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit
-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit
-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit
-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit
-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit
-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit
Enter your choice from above List: 4
CONCLUSION:
Subject :-
Signature
Experiment No. Date of Performance :-
Title :- Write Code and Understand the Concept Array In Data Structure.
THEORY:-
INTRODUCTION OFARRAY
An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together. This makes it easier to calculate the position of
each element by simply adding an offset to a base value, i.e., the memory location of the first
element of the array (generally denoted by the name of the array). An array in C is a fixed-
size collection of similar data items stored in contiguous memory locations. It can be used to
store the collection of primitive data types such as int, char, float, etc., and also derived and
user-defined data types such as pointers, structures, etc.
ARRAY DECLARATION
In C, we have to declare the array like any other variable before using it. We can declare an array
by specifying its name, the type of its elements, and the size of its dimensions. When we declare
an array in C, the compiler allocates the memory block of the specified size to the array name.
arrays are static in nature, i.e., they are allocated memory at the compile time.
Syntax of Array Declaration
data_typearray_name [size]; or
data_typearray_name [size1] [size2]...[sizeN];...........where N is the number of dimensions.
ARRAY INITIALIZATION
Initialization in C is the process to assign some initial value to the variable. When the array is
declared or allocated memory, the elements of the array contain some garbage value. So, we need
to initialize the array to some meaningful value. There are multiple ways in which we can
initialize an array in C.
index 0 and the last element is at N – 1 where N is the number of elements in the array.
C Array Traversal
Traversal is the process in which we visit every element of the data structure. For C array
traversal, we use loops to iterate through each element of the array.
Array Traversal using for Loop
for (int i = 0; i< N; i++) {
array_name[i];
}
TYPES OF ARRAY IN C
There are two types of arrays based on the number of dimensions it has. They are as
follows: 1) One Dimensional Arrays (1D Array)
2) Multidimensional Arrays
2. MULTIDIMENSIONAL ARRAY IN C
Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some
of the popular multidimensional arrays are 2D arrays and 3D arrays. We can declare
arrays with more dimensions than 3d arrays but they are avoided as they get very
complex and occupy a large amount of space.
3. TWO-DIMENSIONAL ARRAY IN C
A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions.
They can be visualized in the form of rows and columns organized in a two-dimensional
plane.
Syntax of 2D Array in C
array_name[size1] [size2];
Here,
size1: Size of the first dimension.
size2: Size of the second dimension.
PROPERTIES OF ARRAYS-
It is very important to understand the properties of the C array so that we can avoid bugs
while using it. The following are the main properties of an array in C:
ALGORITHM OF PROGRAM
1) Start
2) Create class Testarray
3) Initialize main () method.
4) Initialize int variable array a[] having value 5.
5) Specify value for each bit i.e. a[0]=1and so on.
6) Generate for loop such as for(int i=0;i<a.length;i++);
7) Print all the numbers of array.
8) End .
C PROGRAM-
class Testarray{
public static void main(String args[]){
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
OUTPUT OF PROGRAM-
10
20
70
40
50
CONCLUSION:
Subject :-
Signature
Experiment No. Date of Performance :-
Title :- Write Code and Understand the Concept Graphs, Trees in Data Structure
Objective:-Write Code and Understand the Concept Graphs, Trees in Data Structure.
THEORY:-
Both Trees and Graphs are types of non−linear data structures. They are different from each
other in the context of their types of connections and loop formation. That means, a tree
structure is connected such that it can never have loops, whereas a graph structure follows a
network model and may have loops.
TREE-
A Tree is a non−linear data structure that is used to represent hierarchy. It is a set of nodes
that are joined together to form a hierarchy. In a tree structure, only one path is allowed
between two nodes or vertices. The tree structure has an exactly one root node, where the
root node is the topmost node in the structure and it does not have any parent node. Loops
are not allowed in a tree structure, therefore it has (n−1) edges, where is the number of
nodes. Since a tree structure does not form any loops, it is a hierarchical type model.
There are three traversal techniques used in the tree structure which are pre−order,
in−order, and post−order. The tree structure is comparatively a less complex type of
non−linear data structure
GRAPH-
Graph is also a non−linear data structure used in software engineering. Graphs are used to
represent various types of physical structures. A graph consists of a group of nodes (or
vertices) and set of edges. Each edge connect the two nodes. On the graph, the nodes are
represented by a point or a circle, and the edges are represented by line segments or arcs. In a
graph structure, more than one paths are allowed between vertices. Graphs can also have
loops, therefore, they do not have a root node. Graphs follow the network model. There are
two traversal techniques used in the graph that are breadth−first search and depth−first
search. Another important point about graphs is that we can defined number of edges in the
graph. Graph structure has relatively more complex structure.
C PROGRAM-
struct node
{
int info;
struct node *left, *right;
};
struct node *createnode(int key)
{
struct node *newnode = (struct node*)malloc(sizeof(struct
node)); newnode->info = key;
newnode->left = NULL;
newnode->right =
NULL; return(newnode);
}
static int count = 0;
int countnodes(struct node *root)
{
if(root != NULL)
{
countnodes(root->left);
count++;
countnodes(root->right);
}
return count;
}
// Main Function
int main()
{
/* Creating first Tree. */
struct node *newnode = createnode(25);
newnode->left = createnode(27);
newnode->right = createnode(19);
newnode->left->left = createnode(17);
newnode->left->right = createnode(91);
newnode->right->left = createnode(13);
newnode->right->right = createnode(55);
printf("Number of nodes in tree 1 = %d ",countnodes(newnode));
printf("\n");
count = 0;
/* Creating second Tree. */
struct node *root = createnode(15);
newnode->left = createnode(27);
newnode->right = createnode(19);
printf("Number of nodes in tree 1 = %d ",countnodes(newnode));
printf("\n");
count = 0;
return 0;
}
OUTPUT OF PROGRAM -
GRAPHS
The idea is to use a square Matrix of size NxN to create Adjacency Matrix. Below are the
steps:-
1) Create a 2D array(say Adj[N+1][N+1]) of size NxN and initialise all value of
this matrix to zero.
2) For each edge in arr[][](say X and Y), Update value
at Adj[X][Y] and Adj[Y][X] to 1, denotes that there is aedge between X and Y.
3) Display the Adjacency Matrix after the above operation for all the pairs
in arr[][].
#include <stdio.h>
// Find X and Y of
Edges int x = arr[i][0];
int y = arr[i][1];
// Update value to 1
Adj[x][y] = 1;
Adj[y][x] = 1;
}
}
// Driver Code
int main()
{
// Number of
vertices N = 5;
// Given Edges
int arr[][2] = { { 1, 2 }, { 2, 3 },
{ 4, 5 }, { 1, 5 } };
// Number of Edges
M = sizeof(arr) / sizeof(arr[0]);
createAdjMatrix(Adj, arr);
return 0;
}
OUTPUT OF PROGRAM –
01001
10100
01000
00001
10010
CONCLUSION:-
Subject :-
Signature
Experiment No. Date of Performance :-
Title :- Write Code and Understand the Concept Hashing, Hash Table
in Data Structure
OBJECTIVE:- Write Code and Understand the Concept Hashing, Hash Table in
Data Structure
SOFTWARE REQUIREMENT:- Turbo C/C++ Compiler
HARDWARE REQUIREMENT:- Windows OS, Minimum 8 GB RAM…etc
THEORY-
INTRODUCTION OF HASHING –
Hashing is a technique that involves converting a large amount of data into a fixed-size
value or a smaller value known as a hash. The hash is generated through a hash function,
which maps the input data to an output hash. The resulting hash value can then be used to
efficiently search, retrieve, and compare data within large data sets.
Hashing is a technique used in computer programming to quickly search and retrieve data
from large datasets. In C programming, hashing is often used to implement hash tables or
associative arrays. Hashing can be implemented using several different methods, including
the division method, multiplication method, and the folding method.
Hashing is useful for several reasons. Firstly, it can reduce the amount of memory required
to store large data sets by converting the data into a smaller value. Secondly, it can improve
the performance of algorithms by allowing for faster searching and retrieval of data. Finally,
it can help to ensure data integrity by detecting duplicate data and preventing collisions
(when two different keys map to the same index).
Process of Hashing-
The process of hashing involves three main steps: creating the hash function, generating the
hash value, and storing the data in the hash table.
1) Creating the hash function involves designing an algorithm that maps the input data to a
fixed-size value. This algorithm should be designed to distribute the data evenly across the
hash table to reduce the likelihood of collisions.
2) Once the hash function is created, the next step is to generate the hash value for the data.
This involves passing the data through the hash function, which returns a fixed-size hash
value. This value is then used as an index within the hash table to store the data.
3) Storing the data in the hash table involves placing the data in the corresponding location
within the array. If a collision occurs (i.e. if two different keys map to the same index), the
hash table may use a technique called chaining to store both keys in the same index. In
chaining, a linked list is created for each index, and the keys are added to the linked list.
ADVANTAGES-
o Hashing provides fast data retrieval and search times.
o Hashing is relatively simple to implement in C and can be used to build complex data
structures.
o Hashing can also be used for data security purposes, such as password storage or data
encryption.
o Hash tables provide constant-time lookup, insertion, and deletion operations.
DISADVANTAGES:
o Hashing collisions can occur, which can lead to reduced performance and longer
search times.
o Hashing requires a good hash function that can evenly distribute the data across the
hash table. Creating a good hash function can be challenging and time-consuming.
o Hashing can consume a lot of memory
EXPLANATION OF FUNCTIONS:
INSERTION: Inserts the key-value pair at the head of a linked list which is present at
the given bucket index.
HASHFUNCTION: Gives the bucket index for the given key. Our hash function =
ASCII value of character * primeNumberx. The prime number in our case is 31 and
the value of x is increasing from 1 to n for consecutive characters in a key.
DELETION: Deletes key-value pair from the hash table for the given key. It deletes
the node from the linked list which holds the key-value pair.
This implementation does not use the rehashing concept. It is a fixed-sized array of
linked lists.
ALGORITHM OF PROGRAM-
if(array[key] == -1)
{
array[key] = val;
printf("%d inserted at array[%d]\n", val,key);
}
else
{
printf("Collision : array[%d] has element %d already!\n",key,array[key]);
printf("Unable to insert %d\n",val);
}
}
void del(int val)
{
void print()
{
int i;
for(i = 0; i< size; i++)
printf("array[%d] = %d\n",i,array[i]);
}
int main()
{
init();
insert(10);
insert(4);
insert(2);
insert(3);
printf("Hash table\n");
print();
printf("\n");
return 0;
}
OUTPUT OF PROGRAM-
10 inserted at
array[3] 4 inserted at
array[4] 2 inserted at
array[2]
Collision : array[3] has element 10
already! Unable to insert 3
Hash table
array[0] = -1
array[1] = -1
array[2] = 2
array[3] = 10
array[4] = 4
array[5] = -1
array[6] = -1
CONCLUSION-
Subject :-
Signature
Experiment No. Date of Performance :-
LINEAR SEARCHING - In the linear search algorithm, we traverse through the data
structure from any one point and traverse until the data item is found in the data structure.
Linear Search is defined as a sequential search algorithm that starts at one end and goes
through each element of a list until the desired element is found, otherwise the search
continues till the end of the data set.
PROGRAM EXPLANATION
C PROGRAM-
//C program to get input of N numbers from user and perform linear search
#include <stdio.h>
void main()
{
int num;
int i, srch, found = 0;
else
printf("Element %d is not present in the array\n",srch);
}
OUTPUT OF PROGRAM-
BINARY SEARCH-
Fig: Example of Binary Search Algorithm Fig: Finding the middle index “mid”
ALGORITHM OF BINARY SEARCH PROGRAM-
1) Start
2) Declare the variable key for storing the element we are searching for.
3) Find the Mid by Using formula (Low + High)/2
4) Compare the middle element of the search space with the key.
5) If the key is found at middle element, the process is terminated.
6) If the key is not found at middle element, choose which half will be used as the
next search space.
7) If the key is smaller than the middle element, then the left side is used for next
search.
8) If the key is larger than the middle element, then the right side is used for next
search.
9) This process is continued until the key is found or the total search space is
exhausted.
10) End
C PROGRAM-
//C program to get input of N numbers from user and perform Binary Search
#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elements:- ");
scanf("%d",&n);
low = 0;
high = n - 1;
mid = (low+high)/2;
while (low <= high)
{ if(array[mid] <
key) low = mid + 1;
else if (array[mid] == key) {
printf("%d is found at location %d", key,mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list", key);
return 0;
}
Output of Program-
Enter 7 integers:- 2 4 6 8 10 12 16
8 is found at location 4
Enter 7 integers:- 9 8 7 6 5 4 2
CONCLUSION-
Subject :-
Signature
Experiment No. Date of Performance :-
Title :- Write Code and Understand the Concept Sorting Algorithms (any two)
Objective:-Write Code and Understand the Concept Sorting Algorithms (any two).
If we have the array as {40,10,50,70,30}and we apply bubble sort to sort the array, then the
resultant array after each iteration will be as follows:
#include <stdio.h>
void main()
{
int array[10];
int i, j, num, temp;
INSERTION SORT-
Step 1 -If the element is the first element, assume that it is already sorted. Return 1.
Step 2 - Pick the next element, and store it separately in a key.
Step 3 - Now, compare the key with all elements in the sorted array.
Step 4 -If the element in the sorted array is smaller than the current element,
Then move to the next element. Else, shift greater elements in the
array towards the right.
Step 5 -Insert the value.
Step 6 -Repeat until the array is sorted.
#include <stdio.h>
int main(void)
{
int n, i, j,
temp; int
arr[64];
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (i = 0; i< n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1; i< n; i++)
{
j = i;
while (j > 0 &&arr[j - 1] >arr[j])
{
temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i< n; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
6
7
8
9
CONCLUSION-
Subject :-
Signature
Experiment No. Date of Performance :-
Title :- Write Code and Understand the Concept Algorithm Technique on Greedy
Approach
Greedy Algorithm-
A greedy algorithm is an approach for solving a problem by selecting the best option
available at the moment. It doesn't worry whether the current best result will bring the overall
optimal result. The algorithm never reverses the earlier decision even if the choice is wrong.
It works in a top-down approach. This algorithm may not produce the best result for all the
problems. It's because it always goes for the local best choice to produce the global best
result. However, we can determine if the algorithm can be used with any problem if the
problem has the following properties:
If an optimal solution to the problem can be found by choosing the best choice at each step
without reconsidering the previous steps once chosen, the problem can be solved using a
greedy approach. This property is called greedy choice property.
2) Optimal Substructure-
If the optimal overall solution to the problem corresponds to the optimal solution to its
subproblems, then the problem can be solved using a greedy approach. This property is
called optimal substructure.
Advantages of greedy approach-
Drawback of Greedy Approach- As mentioned earlier, the greedy algorithm doesn't always
produce the optimal solution. This is the major disadvantage of the algorithm.
o Candidate set: A solution that is created from the set is known as a candidate set.
o Selection function: This function is used to choose the candidate or subset which can
be added in the solution.
o Feasibility function: A function that is used to determine whether the candidate or
subset can be used to contribute to the solution or not.
o Objective function: A function is used to assign the value to the solution or the partial
solution.
o Solution function: This function is used to intimate whether the complete function has
been reached or not.
GREEDY ALGORITHM -
1. To begin with, the solution set (containing answers) is empty.
2. At each step, an item is added to the solution set until a solution is reached.
3. COIN-CHANCE-
GREEDY(n) 4. Coin= [20,10,5,1]
5. I=0
6. While(n)
7. If coins [i]>
n 8. i++
9. else
10. print coins [i]
11. n = n-coins [i]
12. End
PROGRAM APPROACH-
if coins [i] > n → We are starting from the 0th element (element with the largest value) and
checking if we can use this coin or not. If the value of this coin is greater than the value to be
made, then we are moving to the next coin - i++.
If the value of the coin is not greater than the value to be made, then we can take this coin.
So, we will take it. Let's just print the value right here to indicate we have taken it,
otherwise, we can also append these value in an array and return it.
while (n)
...
else
print coins[i]
Now, the value to be made is reduced by coins[i] i.e., n-coins[i].
C PROGRAM-
#include <stdio.h>
void coin_change_greedy(int n) {
int coins[] = {20, 10, 5, 1};
int i=0;
while(n) {
if(coins[i] > n)
{
i++;
}
else { printf("%d\
t",coins[i]);
n = n-coins[i];
}
}
printf("\n");
}
int main() {
int i;
for(i=1; i<=20; i++) {
coin_change_greedy(i);
}
return 0;
}
OUTPUT OF PROGRAM-
1
1 1
1 1 1
1 1 1 1
5
5 1
DEPT OF E&C ENGG.
K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON
5 1 1
5 1 1 1
5 1 1 1 1
10
10 1
10 1 1
10 1 1 1
10 1 1 1 1
10 5
10 5 1
10 5 1 1
10 5 1 1 1
10 5 1 1 1 1
20
CONCLUSION-