0% found this document useful (0 votes)
19 views

PDSA Manual

Notes
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

PDSA Manual

Notes
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

K.C.

E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Khandesh College Education Society’s


College of Engineering and Management,
Jalgaon
Department of Electronics and Computer Engineering
A.Y- 2024-25

Lab Manual
Competitive programming lab -Java

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Academic Year:2024-25 Semester :V


Grade
Name of Student :-
Date of
Class: - Roll No. : Completion

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;

The example of declaring the variable is given below:-


a. int a;
b. float b;
c. char c;
Here, a, b, c are variables. The int, float, char are the data types.

Rules for defining variables-


 A variable can have alphabets, digits, and underscore.
 A variable name can start with the alphabet, and underscore only. It can't start with a
digit.
 No whitespace is allowed within the variable name.
 A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names:-int a; , int _ab; , int a30;

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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.

Types Data Types

Basic Data Type int, char, float, double

Derived Data Type array, pointer, structure,


union

Enumeration Data enum


Type

Void Data Type Void

 Basic Data Types -


The basic data types are integer-based and floating-point based. C language supports both
signed and unsigned literals.The memory size of the basic data types may change according
to 32 or 64-bit operating system.

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.

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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;

 Derived Data Type-


Beyond the fundamental data types, C also supports derived data types, including arrays,
pointers, structures, and unions. These data types give programmers the ability to handle
heterogeneous data, directly modify memory, and build complicated data structures.

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

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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-

// C Program to Describe Variable, Data Type and Data Object Concept.


#include<stdio.h>
Int main()
{
int num;
char ch;
float f;

printf(“\n Enter any Character: ”);


scanf(“%d”, &ch);
printf(“\n Enter any Interger Number: ”);
scanf(“%d”, &num);

printf(“\n Enter any Float Number: ”);


DEPT OF E&C ENGG.
K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

scanf(“%d”, &f);

printf(“\n You Have Entered: %c”,ch);


printf(“\n You Have Entered: %d”,num);
printf(“\n You Have Entered: %f”,f);

return 0;
}

OUTPUT OF PROGRAM:

Enter any Character: G


Enter any Interger Number: 15
Enter any Float Number: 15.65

You Have Entered: G


You Have Entered: 15
You Have Entered: 15.65

CONCLUSION:

Signature with Date


Subject Incharge

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Academic Year:2024-25 Semester :


Grade
Name of Student :-
Date of
Class: - Roll No. : Completion

Subject :-
Signature
Experiment No. Date of Performance :-

Title :- Write Code and Understand the Concept Constructor and Relationship

OBJECTIVE:-Write Code and Understand the Concept Constructor and Relationship

SOFTWARE REQUIREMENT:- Turbo C/C++ Compiler


HARDWARE REQUIREMENT:- Windows OS, Minimum 8 GB RAM…etc
THEORY:

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.

The prototype / Syntax of the constructor looks like


<class-name> (list-of-parameters);

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
}

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

CHARACTERISTICS OF CONSTRUCTOR:-

 The name of the constructor is same as its class name.


 Constructors are mostly declared in the public section of the
 Class though it can be declared in the private section of the class.
 Constructors do not return values; hence they do not have a return type.
 A constructor gets called automatically when we create the object of the class.
 Constructors can be overloaded.
 Constructor can not be declared virtual.

TYPES OF CONSTRUCTORS :-

1) Default Constructor

A constructor to which no arguments are passed is called the Default constructor. It is


also called a constructor with no parameters.
2) Parameterized 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

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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:-

1) STEP 1: Start the program.


2) STEP 2: Declare the class as somestructwith empid and *name variables.
3) STEP 3: Declare the “Constructor” in class and create object as str1.
4) STEP 4: Allocate the Memory for declared variables by using malloc() function
5) STEP 5: Define Constructor AND initialization the Variables empid and *name
6) STEP 6: Write main function for display values empid and *name
7) STEP 7: Main function declaration and definition
8) STEP 8: Create Function for deallocate memory
9) STEP 9: Display the value of Variable using class object.
10) STEP 10: Stop the program.

C PROGRAM:-

// Program to display the value of variable by using Constructor object


#include<stdio.h>
#include<stdlib.h>
struct somestruct
{
int empid;
char * name;
};

struct somestruct * str1;


void attribute ((constructor)) a_constructor()
{
str1 =(struct somestruct *) malloc (sizeof(struct somestruct));
str1 -> empid = 202324;
str1 -> name = "Robert William";
}

void attribute ((destructor)) a_destructor()


{
free(str1);
}

int main()
{
printf("ID = %d\nName = %s\n", str1 ->empid,str1 -> name);
return 0;
}

OUTPUT OF PROGRAM-

ID = 202324
Name = Robert William

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

CONCLUSION:

Signature with Date


Subject In charge

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Academic Year: Semester :


Grade
Name of Student :-
Date of
Class: - Roll No. : Completion

Subject :-
Signature
Experiment No. Date of Performance :-

Title :- Write Code and Understand the Concept List In Data Structure.

OBJECTIVE:-Write Code and Understand the Concept List In Data Structure.

SOFTWARE REQUIREMENT:- Turbo C/C++ Compiler

HARDWARE REQUIREMENT:- Windows OS, Minimum 8 GB RAM…etc

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 -

//A list of integers


my_list = [1, 2, 3, 4,
5] print(my_list)

IMPORTANCE AND APPLICATION OF 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:

 Sorting Algorithms: Lists are essential to constructing efficient sorting algorithms


such as quick sort and merge sort.
 Data Analytics: Lists are often used to represent datasets in data analytics and
machine learning.
 Database Management: Lists can construct complex data structures such as trees and
graphs used in database systems.

EXPLORING LINKED LIST DATA STRUCTURE –

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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.

Advantages of Using Linked List Data Structures -

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 -

// Linked list implementation in


C #include <stdio.h>
#include <stdlib.h>

// 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));

// Assign value values


one->value = 45;
two->value = 72;
three->value = 93;
four->value = 21;
five->value = 56;

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

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

head = one;
printLinkedlist(head);
}

OUTPUT OF PROGRAM- 45 72 93 21 56

CONCLUSION:

Signature with Date


Subject In charge

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Academic Year: Semester :


Grade
Name of Student :-
Date of
Class: - Roll No. : Completion

Subject :-
Signature
Experiment No. Date of Performance :-

Title :- Write Code and Understand the Concept Queue in Data Structure

Objective:-Write Code and Understand the Concept Queue in Data Structure.

SOFTWARE REQUIREMENT:- Turbo C/C++ Compiler

HARDWARE REQUIREMENT:- Windows OS, Minimum 8 GB RAM…etc

THEORY:

QUEUE IN DATA STRUCTURE-


The Queue is a linear data structure that follows the FIFO pattern in which the element
inserted first at the queue will be removed first.
There are real-world examples of queues, the ticket row for trains, customers waiting in a
row, etc.
Here is the FIFO representation of the queue.

Basic Queue Operations:


 Enqueue: Elements are added at the end of queue.
 Dequeue: Removes the element from the beginning of the queue.
 isEmpty(): Check if the queue is empty or not.
 isFull(): Check if the queue is full or not.
 Peek(): Bring the item to the top of the queue without removing it.

Method to Implement Queue Program in C using Array


 In this implementation, we are using a structure in which an array of integers is taken.
There are two other variables front and rear which are used to store the array index
for dequeue and enqueue respectively.
 Initially front and rear have value -1 which means that the queue is empty.
On enqueue operation, the rear will be moved by one index forward and the data will

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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-

//C Program to Implement a Queue using an


Array #include <stdio.h>
#define MAX 50

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");

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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
{

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

printf("Element deleted from queue is : %d\n", queue_array[front]);


front = front + 1;
}
} // End of delete()

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

Enter your choice from above List: 1


Enter the Number to Inset the element in queue : 52……. /*again press ‘Enter’ key on
keyboard then the msg will be displayed as follows */
-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit

Enter your choice from above List: 1


Enter the Number to Inset the element in queue : 25

-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Enter your choice from above List: 1


Enter the Number to Inset the element in queue : 95

-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit

Enter your choice from above List: 3


Queue Elements is :- 52 25 95

-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit

Enter your choice from above List: 2


Element deleted from queue is : 52

-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit

Enter your choice from above List: 3


Queue Elements is :- 25 95

-*--Queue Operations--*-
1.Insert / Enqueue
2.Delete / Dequeue
3.Display
4.Quit
Enter your choice from above List: 4

CONCLUSION:

Signature with Date


Subject In charge

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Academic Year:2024-25 Semester :V


Grade
Name of Student :-
Date of
Class: - Roll No. : Completion

Subject :-
Signature
Experiment No. Date of Performance :-

Title :- Write Code and Understand the Concept Array In Data Structure.

Objective:-Write Code and Understand the Concept Array In Data Structure.

SOFTWARE REQUIREMENT:- Java 1.80

HARDWARE REQUIREMENT:- Windows OS, Minimum 8 GB RAM…etc

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.

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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.

1. ARRAY INITIALIZATION WITH DECLARATION


In this method, we initialize the array along with its declaration. We use an initializer list to
initialize multiple elements of the array. An initializer list is the list of values enclosed within
braces { } separated b a comma.
data_type array_name [size] = {value1, value2, ... valueN};

2. ARRAY INITIALIZATION WITH DECLARATION WITHOUT SIZE


If we initialize an array using an initializer list, we can skip declaring the size of the array as
the compiler can automatically deduce the size of the array in these cases. The size of the array in
these cases is equal to the number of elements present in the initializer list as the compiler can
automatically deduce the size of the array.
data_type array_name[] = {1,2,3,4,5};
The size of the above arrays is 5 which is automatically deduced by the
compiler. 3. ARRAY INITIALIZATION AFTER DECLARATION (USING
LOOPS)
We initialize the array after the declaration by assigning the initial value to each element
individually. We can use for loop, while loop, or do-while loop to assign the value to each element
of the array.
for (int i = 0; i< N; i+
+) { array_name[i] =
valuei;
}
ACCESS ARRAY ELEMENTS

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON
We can access any element of an array in C using the array subscript operator [ ] and the index
value i of the element.
array_name [index];
One thing to note is that the indexing in the array always starts with 0, i.e., the first element is at

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

index 0 and the last element is at N – 1 where N is the number of elements in the array.

UPDATE ARRAY ELEMENTS


We can update the value of an element at the given index i in a similar way to accessing an
element by using the array subscript operator [ ] and assignment operator =
array_name[i] = new_value;

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

1. ONE DIMENSIONAL ARRAY IN C


The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have
only one dimension.
Syntax of 1D Array in C
array_name [size];

2. MULTIDIMENSIONAL ARRAY IN C

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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:

1. Fixed Size-The array is a fixed-size collection of elements.


2. Homogeneous Collection-We can only store one type of element in an array.
3. Indexing in Array- The array index always starts with 0. It means that the index of the
first element of the array will be 0 and the last element will be N – 1.
4. Dimensions of an Array- It is the number of directions in which you can grow the
array size.
5. Contiguous Storage- All the elements in the array are stored continuously one after
another in the memory.
6. Random Access-The array provides random access to its element i.e we can get to a
random element at any index of the array

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 .

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

C PROGRAM-

1. // Java Program to illustrate how to declare, instantiate, initialize


and traverse the Java array.

class Testarray{
public static void main(String args[]){

int a[]=new int[5];//declaration and instantiation


a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;

//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:

Signature with Date


Subject In charge

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Academic Year: Semester :


Grade
Name of Student :-
Date of
Class: - Roll No. : Completion

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.

SOFTWARE REQUIREMENT:- Turbo C/C++ Compiler

HARDWARE REQUIREMENT:- Windows OS, Minimum 8 GB RAM…etc

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

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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.

Solution Of Trees Program


1. In order to count the number of nodes in a tree we just need to traverse the whole tree once.
We can use any of the traversal techniques to count the number of nodes.
2. We have to take a count variable and initialize it with 0 and for each node which we traverse we
just have to increase the value of count.
FUNCTION USED IN PROGRAM
Program Contains Two Important Functions which is given below.
1. createnode(key);
This function helps to create a new node by allocating it a memory dynamically. It has just
one parameter which is “key” which assigns value to the node thereby creating a fresh node
having left and right child as “NULL”.
2. countnodes(struct node *root);
In this function we have traversed the left and right subtree and increased the count variable
which counts the total number of nodes present in the left and the right subtree. The traversal
technique which we have used here is inorder traversal of a tree, by first passing root->left
then instead of printing the root->data as a next step of inorder traversal we increase the count
variable and then we have passed the root->right to traverse the right subtree and count the total
number of nodes present in the right subtree.
ALGORITHAMOF OF PROGRAM-
1) Make a pointer which points to current node
2) Continue steps above till the current node pointer is not null
3) If the left of the pointer is NULL , then increment count and move to right.
4) If left pointer is not null , make another temporary pointer to one left of current pointer
and Move towards right till it's not null.

C PROGRAM-

*** Trees Program ***


// C Program For Counting The Number Of Nodes In A Tree
#include <stdio.h>
#include <stdlib.h>

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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;

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

return 0;
}

OUTPUT OF PROGRAM -

Number of nodes in tree 1 = 7


Number of nodes in tree 2 = 3

GRAPHS

APPROACH/ALGORITHM OF GRAPH PROGRAM-

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[][].

*** GRAPH PROGRAM ***

//C program to implement Adjacency Matrix of a given Graph

#include <stdio.h>

// N is vertices and M is Edges


int N, M;

// Function to create Adjacency Matrix


void createAdjMatrix(int Adj[][N + 1],
int arr[][2])
{

// Initialise all value to this


// Adjacency list to zero
for (int i = 0; i< N + 1; i++) {

for (int j = 0; j < N + 1; j++)


{ Adj[i][j] = 0;
}
}

// Traverse the array of Edges

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

for (int i = 0; i< M; i++) {

// 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;
}
}

// Function to print the created


// Adjacency Matrix
void printAdjMatrix(int Adj[][N + 1])
{

// Traverse the Adj[][]


for (int i = 1; i< N + 1; i++) {
for (int j = 1; j < N + 1; j++)
{

// Print the value at Adj[i]


[j] printf("%d ", Adj[i][j]);
}
printf("\n");
}
}

// 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]);

// For Adjacency Matrix


int Adj[N + 1][N + 1];

// Function call to create


// Adjacency Matrix
DEPT OF E&C ENGG.
K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

createAdjMatrix(Adj, arr);

// Print Adjacency Matrix


printAdjMatrix(Adj);

return 0;
}

OUTPUT OF PROGRAM –

01001
10100
01000
00001
10010

CONCLUSION:-

Signature with Date


Subject In charge

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Academic Year: Semester :


Grade
Name of Student :-
Date of
Class: - Roll No. : Completion

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.

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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

MAJOR FUNCTIONS USED IN GIVEN PROGRAM-


1) Insertion
2) Search
3) Hash Function
4) Delete

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.

 SEARCH: Search for the value of the given key.

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

 This implementation does not use the rehashing concept. It is a fixed-sized array of
linked lists.

ALGORITHM OF PROGRAM-

1) Create an array of structure, data (i.e a hash table).


2) Take a key to be stored in hash table as input.
3) Corresponding to the key, an index will be generated.
4) In case of absence of data in that index of array, create one and insert the data
item (key and value) into it and increment the size of hash table.
5) In case the data already exists, the new data cannot be inserted if the already present
data does not match given key.
6) To display all the elements of hash table, data at each index is extracted and
elements (key and value) are read and printed.
7) To remove a key from hash table, we will first calculate its index and extract
its data, delete the key in case it matches the given key.
8) Exit
C PROGRAM-

//Implementation of a hash table using


arrays #include<stdio.h>
#define size 7
int array[size];
void init()
{
int i;
for(i = 0; i< size; i++)
array[i] = -1;
}

void insert(int val)


{
int key = val % size;

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)
{

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

int key = val % size;


if(array[key] ==
val) array[key] = -1;
else
printf("%d not present in the hash table\n",val);
}

void search(int val)


{
int key = val % size;
if(array[key] == val)
printf("Search Found\n");
else
printf("Search Not Found\n");
}

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");

printf("Deleting value 10..\n");


del(10);
printf("After the deletion hash table\n");
print();
printf("\n");

printf("Deleting value 5..\n");


del(5);
printf("After the deletion hash table\n");
print();
printf("\n");

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

printf("Searching value 4..\n");


search(4);
printf("Searching value 10..\n");
search(10);

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

Deleting value 10..


After the deletion hash table
array[0] = -1
array[1] = -1
array[2] = 2
array[3] = -1
array[4] = 4
array[5] = -1
array[6] = -1

Deleting value 5..


5 not present in the hash
table After the deletion hash
table array[0] = -1
array[1] = -1
array[2] = 2
array[3] = -1
array[4] = 4
array[5] = -1
array[6] = -1

Searching value 4..


Search Found
Searching value 10..
DEPT OF E&C ENGG.
K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Search Not Found

CONCLUSION-

Signature with Date


Subject In charge

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Academic Year: Semester :


Grade
Name of Student :-
Date of
Class: - Roll No. : Completion

Subject :-
Signature
Experiment No. Date of Performance :-

Title :- Write Code and Understand the Concept Search Algorithms

OBJECTIVE:-Write Code and Understand the Concept Search Algorithms

SOFTWARE REQUIREMENT:- Turbo C/C++ Compiler


HARDWARE REQUIREMENT:- Windows OS, Minimum 8 GB RAM…etc
THEORY-

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.

Fig- Linear Search Algorithm


ALGORITHM FOR LINEAR SEARCH-
1) Start
2) Declare the variable key for storing the element we are searching for.
3) Check each element in the list by comparing it to the key.
4) If any element is equal to the key, return its index.
If we reach the end of the list without finding the element equal to the key return
the Massage “Element is not found in the List”.
5) End

PROGRAM EXPLANATION

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

1. In Linear search, we search an element or value in a given array by traversing


the array from the starting, till the desired element or value is found.
2. The array is searched sequentially and the position is returned if the key element
to be searched is available in the array, otherwise -1 is returned.
3. Here in this C Program we have not made any function specifically for linear
search, rather we can look for presence of element in an array in the main function
itself.
4. We traverse the array from the 0th index in increasing order of index, if we find
the element we break the loop there itself and print the position of the element in
the array, but if the element requested is not there in array, we simply print that
“Element is not present in the array”.
5. If we’d have created a separate function for linear search and the element could
not be found in the array, we would have returned -1 in that case denoting absence
of the element.

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;

printf("Enter the number of elements:- ");


scanf("%d", &num);
int array[num];
printf("Enter the elements one by one- \n");
for (i = 0; i< num; i++)
{
scanf("%d", &array[i]);
}

printf("Enter the element to be searched in the Array:- ");


scanf("%d", &srch);

/* Linear search begins */


for (i = 0; i<num ;i++)
{
if (srch == array[i] )
{
found = 1;
break;
}
}
if (found == 1)
printf("Element %d is present at %d position in the array",srch,i+1);
DEPT OF E&C ENGG.
K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

else
printf("Element %d is not present in the array\n",srch);
}
OUTPUT OF PROGRAM-

Enter the number of elements:- 5


Enter the elements one by one-
96543
Enter the element to be searched in the Array:- 4
Element 4 is present at 4 position in the array

Enter the number of elements:- 6


Enter the elements one by one-
973150
Enter the element to be searched in the Array:- 2
Element 2 is not present in the array

BINARY SEARCH-

Binary Search is defined as a searching algorithm used in a sorted array by repeatedly


dividing the search interval in half. The idea of binary search is to use the information that
the array is sorted and reduce the time complexity to O(log N). Binary Search is used in a
Data Structure when The data structure must be sorted. and Access to any element of the
data structure takes constant time.

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.

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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);

printf("\nEnter %d integers:- ", n);


for(i = 0; i< n; i++)
scanf("%d",&array[i]);

printf("\n Enter value to find:- ");


scanf("%d", &key);

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 number of elements:- 7

Enter 7 integers:- 2 4 6 8 10 12 16

Enter value to find:- 8

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

8 is found at location 4

Enter number of elements:- 7

Enter 7 integers:- 9 8 7 6 5 4 2

Enter value to find:- 3

Not found! 3 isn't present in the list

CONCLUSION-

Signature with Date


Subject In charge

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Academic Year: Semester :


Grade
Name of Student :-
Date of
Class: - Roll No. : Completion

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).

SOFTWARE REQUIREMENT:- Turbo C/C++ Compiler


HARDWARE REQUIREMENT:- Windows OS, Minimum 8 GB RAM…etc
THEORY-
BUBBLE SORT-
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based
algorithm in which each pair of adjacent elements is compared and the elements are swapped
if they are not in order. This algorithm is not suitable for large data sets as its average and
worst case complexity are of Ο(n2) where n is the number of items.
Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the
intended order. It is called bubble sort because the movement of array elements is just like
the movement of air bubbles in the water. Bubbles in water rise up to the surface; similarly,
the array elements in bubble sort move to the end in each iteration.
Bubble short is majorly used where -complexity does not matter and simple and shortcode is
preferred
Bubble Sort Example:-

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:

Original array: {40, 10, 50, 70, 30}


Array after first iteration 10 -> 40 -> 50 -> 30 -> 70
Array after second iteration 10 -> 40 -> 30 -> 50 -> 70
Array after third iteration 10 -> 30 -> 40 -> 50 -> 70
Array after fourth iteration 10 -> 30 -> 40 -> 50 -> 70
Sorted array is 10 30 40 50 70

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

BUBBLE SORT ALGORITHM


1. Start
2. In Bubble sort algorithm we compare the first two elements of an array and swap them
3.If we want to sort the elements of array in ascending order and if the first element
is greater than second then, we need to swap the elements.
4. If the first element is smaller than second, we don’t need to swap the elements.
This process go on until last and second last element is compared and
swapped.
5. End

C PROGRAM OF BUBBLE SORT-


/* C program to sort Numbers in ascending order using Bubble sort and print
both the given and the sorted array */

#include <stdio.h>
void main()
{
int array[10];
int i, j, num, temp;

printf("How many numbers do you want to sort \


n"); scanf("%d", &num);

printf("Enter the elements one by one \n");


for (i = 0; i< num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is \n");
for (i = 0; i< num; i++)
{
printf("%d\n", array[i]);
}
// Bubble sorting begins
for (i = 0; i< num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] >array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
DEPT OF E&C ENGG.
K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

for (i = 0; i< num; i++)


{
printf("%d\n", array[i]);
}
}
OUTPUT OF PROGRAM-
How many numbers do you want to sort
6
Enter the elements one by one
753249
Input array is
7
5
3
2
4
9
Sorted array is...
2
3
4
5
7
9

INSERTION SORT-

This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which


is always sorted. For example, the lower part of an array is maintained to be sorted. An
element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and
then it has to be inserted there. Hence the name, insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into the sorted
sub-list (in the same array). This algorithm is not suitable for large data sets as its average
and worst case complexity are of Ο(n2), where n is the number of items.

CHARACTERISTICS OF INSERTION SORT


 This algorithm is one of the simplest algorithms with a simple implementation
 Basically, Insertion sort is efficient for small data values
 Insertion sort is adaptive in nature, i.e. it is appropriate for data sets that are already
partially sorted.

ALGORITHM OF 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,

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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.

C PROGRAM OF INSERTION SORT-

/* C Program to sort an array in ascending order using Insertion Sort */

#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;
}

OUTPUT OF PROGRAM- Enter number of elements: 7


Enter 7 integers: 7 9 8 6 4 5 2

Sorted list in ascending order using Insertion Sort:-


2
4
5
DEPT OF E&C ENGG.
K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

6
7
8
9

CONCLUSION-

Signature with Date


Subject In charge

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

Academic Year: Semester :


Grade
Name of Student :-
Date of
Class: - Roll No. : Completion

Subject :-
Signature
Experiment No. Date of Performance :-

Title :- Write Code and Understand the Concept Algorithm Technique on Greedy
Approach

OBJECTIVE:-Write Code and Understand the Concept Algorithm Technique on


Greedy Approach .
SOFTWARE REQUIREMENT:- Turbo C/C++ Compiler
HARDWARE REQUIREMENT:- Windows OS, Minimum 8 GB RAM…etc
THEORY-
INTRODUCTION- The Greedy method is the simplest and straightforward approach. It is
not an algorithm, but it is a technique. The main function of this approach is that the decision
is taken on the basis of the currently available information. Whatever the current information
is present, the decision is made without worrying about the effect of the current decision in
future.

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:

1) Greedy Choice Property-

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.

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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-

1) The algorithm is easier to describe.


2) This algorithm can perform better than other algorithms (but, not in all cases).

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.

The Components That Can Be Used In The Greedy Algorithm Are:

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-

DEPT OF E&C ENGG.


K.C.E’S COLLEGE OF ENGINEERING AND MANAGEMENT, JALGAON

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-

Signature with Date


Subject In charge

DEPT OF E&C ENGG.

You might also like