0% found this document useful (0 votes)
10 views51 pages

Algorithm Design Lab Manual

The document is a practical file for an Algorithm Design Lab at BRCM College of Engineering & Technology, detailing various programming experiments. It includes tasks such as searching in arrays, implementing sorting algorithms, performing operations on strings, and managing data structures like linked lists and binary search trees. Each experiment provides code snippets and outlines the expected operations and outputs.

Uploaded by

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

Algorithm Design Lab Manual

The document is a practical file for an Algorithm Design Lab at BRCM College of Engineering & Technology, detailing various programming experiments. It includes tasks such as searching in arrays, implementing sorting algorithms, performing operations on strings, and managing data structures like linked lists and binary search trees. Each experiment provides code snippets and outlines the expected operations and outputs.

Uploaded by

Monika Sheoran
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

A

Practical File
On
Algorithm Design Lab
(16CSE22CL1)

BRCM COLLEGE OF ENGINEERING & TECHNOLOGY


BAHAL (HARYANA)

Submitted to: - Submitted By: -


[Link] Student Name
[Link] (2nd Sem.)
Branch: - CSE)
INDEX
Sr EXPERIMENT PAGE DATE REMARKS TEACHER’S
No. NO.
SIGNATURE

Write a program to search an element in a two -


1. dimensional array using linear search. 1-2

2. Using iteration & recursion concepts write 3-4


programs for finding the element in the array
Using Binary Search Method.
3. Write a program to perform following 5-7
operations Addition, Subtraction, Multiplication
and Transpose on tables using functions only.
4. Using iteration & recursion concepts write the 8-11
programs for Quick Sort Technique.
5. Write a program to implement the various 12-15
operations on string such as length of string
concatenation, reverse of a string & copy of a
string to another.
6. Write a program for swapping of two numbers 16-18
using call by value and call by
reference strategies.
7. Write a program to implement binary search 19-24
tree. (Insertion and Deletion in Binary search
Tree).

8. Write a program to create a linked list & 25-35


perform operations such as insert, delete,
update, reverse in the link list.
9. Write the program for implementation of a file 36-42
and performing operations such as insert, delete,
update a record in the file.
10. Create a linked list and perform the following 43-47
operations on it: -
a) Add a node
b) Delete a node
EXPERIMENT-1
Write a program to search an element in a two -dimensional array using
linear search.
#include<stdio.h>

#include<conio.h>

void main ()

int a [3][3], i, j, item, found=0, row, col;

clrscr ();

printf ("enter element in 2-d array\n");

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

for (j=0; j<=2; j++)

scanf ("%d”, &item[i][j]);

printf ("enter searched element\n");

scanf ("%d”, &item);

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

for (j=0; j<=2; j++)

if(item==a[i][j])

1
{

found=1;

row=i;

col=j;

break;

if(found==1)

printf ("element is found at %d row and %d col”, row, col);

else

printf ("element is not found");

getch ();

OUTPUT: -

2
EXPERIMENT-2
Using iteration & recursion concepts write programs for finding the element
in the array Using Binary Search Method.

Using Iteration: -

#include<stdio.h>
#include<conio.h>
int iterativeBsearch(int A[], int size, int element);
void main() {
int A[] = {0,12,6,12,12,18,34,45,55,99};
int n=55;
clrscr();
printf("%d is found at Index %d \n",n,iterativeBsearch(A,10,n));
getch();
}
int iterativeBsearch(int A[], int size, int element) {
int start = 0;
int end = size-1;
while(start<=end) {
int mid = (start+end)/2;
if( A[mid] == element) {
return mid;
} else if( element< A[mid] ) {
end = mid-1;
} else {
start = mid+1;
}
}
return -1;
}

OUTPUT: -

3
Using Recursion: -

#include<stdio.h>
#include<stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements\n");
scanf("%d",&n);
printf("Enter %d integers\n", n);
for ( c = 0 ; c < n ; c++ )
scanf("%d",&array[c]);
printf("Enter value to find\n");
scanf("%d",&search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while( first<= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if ( first> last )
printf("Not found! %d is not present in the list.\n", search);
return 0;
}
OUTPUT: -

4
EXPERIMENT-3
Write a program to perform following operations Addition, Subtraction,
Multiplication and Transpose on tables using functions only.

#include<stdio.h>
#include<conio.h>

// function to add two 3x3 table


void add(int m[3][3], int n[3][3], int sum[3][3])
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
sum[i][j] = m[i][j] + n[i][j];
}

// function to subtract two 3x3 table


void subtract(int m[3][3], int n[3][3], int result[3][3])
{
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
result[i][j] = m[i][j] - n[i][j];
}

// function to multiply two 3x3 table


void multiply(int m[3][3], int n[3][3], int result[3][3])
{
for(int i=0; i < 3; i++)
{
for(int j=0; j < 3; j++)
{
result[i][j] = 0; // assign 0
// find product
for (int k = 0; k < 3; k++)
result[i][j] += m[i][k] * n[k][j];
5
}
}
}

// function to find transpose of a 3x3 table


void transpose(int table[3][3], int trans[3][3])
{
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
trans[i][j] = table[j][i];
}

// function to display 3x3 table


void display(int table[3][3])
{
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
printf("%d\t",table[i][j]);

printf("\n"); // new line


}
}

// main function
int main()
{
// table
int a[][3] = { {5,6,7}, {8,9,10}, {3,1,2} };
int b[][3] = { {1,2,3}, {4,5,6}, {7,8,9} };
int c[3][3];
clrscr();

// print both table


printf("First table:\n");
display(a);
printf("Second table:\n");
display(b);

// variable to take choice


int choice;

// menu-driven
do
{
// menu to choose the operation

6
printf("\nChoose the table operation,\n");
printf(" \n");
printf("1. Addition\n");
printf("2. Subtraction\n");
printf("3. Multiplication\n");
printf("4. Transpose\n");
printf("5. Exit\n");
printf(" \n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add(a, b, c);
printf("Sum of table: \n");
display(c);
break;
case 2:
subtract(a, b, c);
printf("Subtraction of table: \n");
display(c);
break;
case 3:
multiply(a, b, c);
printf("Multiplication of table: \n");
display(c);
break;
case 4:
printf("Transpose of the first table: \n");
transpose(a, c);
display(c);
printf("Transpose of the second table: \n");
transpose(b, c);
display(c);
break;
case 5:
printf("Thank You.\n");
default:
printf("Invalid input.\n");
printf("Please enter the correct input.\n");
}
}while(1);
return 0;
}
OUTPUT: -

7
EXPERIMENT: - 4
Using iteration & recursion concepts write the programs for Quick Sort
Technique.

Using Iteration: -

#include <stdio.h>

// A utility function to swap two elements


void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}

/* This function is same in both iterative and recursive*/


int partition(int arr[], int l, int h)
{
int x = arr[h];
int i = (l - 1);

for (int j = l; j <= h - 1; j++) {


if (arr[j] <= x) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[h]);
return (i + 1);

8
}

/* A[] --> Array to be sorted,


l --> Starting index,
h --> Ending index */
void quickSortIterative(int arr[], int l, int h)
{
// Create an auxiliary stack
int stack[h - l + 1];

// initialize top of stack


int top = -1;

// push initial values of l and h to stack


stack[++top] = l;
stack[++top] = h;

// Keep popping from stack while is not empty


while (top >= 0) {
// Pop h and l
h = stack[top--];
l = stack[top--];

// Set pivot element at its correct position


// in sorted array
int p = partition(arr, l, h);

// If there are elements on left side of pivot,


// then push left side to stack
if (p - 1 > l) {
stack[++top] = l;
stack[++top] = p - 1;
}

// If there are elements on right side of pivot,


// then push right side to stack
if (p + 1 < h) {
stack[++top] = p + 1;
stack[++top] = h;
}
}
}

// A utility function to print contents of arr


void printArr(int arr[], int n)
{

9
int i;
for (i = 0; i < n; ++i)
printf("%d ", arr[i]);
}

// Driver program to test above functions


int main()
{
int arr[] = { 4, 3, 5, 2, 1, 3, 2, 3 };
int n = sizeof(arr) / sizeof(*arr);
quickSortIterative(arr, 0, n - 1);
printArr(arr, n);
return 0;
}

OUTPUT: -

Using Recursion: -

#include <stdio.h>

void quicksort (int [], int, int);

int main()
{
int list[50];
int size, i;

printf("How many elements u want to Sort :: ");


scanf("%d", &size);

printf("\nEnter the elements below to be sorted :: \n");

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


{
printf("\nEnter [ %d ] element :: ",i+1);
scanf("%d", &list[i]);
}

quicksort(list, 0, size - 1);

10
printf("\nAfter implementing Quick sort, Sorted List is :: \n\n");

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


{
printf("%d ", list[i]);
}

printf("\n");

return 0;
}

void quicksort(int list[], int low, int high)


{
int pivot, i, j, temp;
if (low < high)
{
pivot = low;
i = low;
j = high;
while (i < j)
{
while (list[i] <= list[pivot] && i <= high)
{
i++;
}
while (list[j] > list[pivot] && j >= low)
{
j--;
}
if (i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
temp = list[j];
list[j] = list[pivot];
list[pivot] = temp;
quicksort(list, low, j - 1);
quicksort(list, j + 1, high);
}
}
OUTPUT: -

11
EXPERIMENT: -5
Write a program to implement the various operations on string such as length
of string concatenation, reverse of a string & copy of a string to another.

Length of String: -

#include <stdio.h>
#include <string.h>
int main()
{
char a[100];
int length;

printf("Enter a string to calculate its length\n");


gets(a);

length = strlen(a);

printf("Length of the string = %d\n", length);

return 0;
}

OUTPUT: -

12
Copy of a string to another: -

#include <stdio.h>
#include <string.h>
int main()
{
char source[1000], destination[1000];

printf("Input a string\n");
gets(source);

strcpy(destination, source);

printf("Source string: %s\n", source);


printf("Destination string: %s\n", destination);

return 0;
}

OUTPUT: -

13
String Concatenation: -

#include <stdio.h>
#include <string.h>
int main()
{
char a[1000], b[1000];

printf("Enter the first string\n");


gets(a);

printf("Enter the second string\n");


gets(b);

strcat(a, b);

printf("String obtained on concatenation: %s\n", a);

return 0;
}

OUTPUT: -

14
Reverse Of a String: -

#include <stdio.h>
#include <string.h>
int main()
{
char s[100];

printf("Enter a string to reverse\n");


gets(s);

strrev(s);

printf("Reverse of the string: %s\n", s);

return 0;
}

OUTPUT: -

15
EXPERIMENT: -6

16
Write a program for swapping of two numbers using call by value and call by
reference strategies.

Swapping of two number using call by value: -

#include <stdio.h>

void swap (int a, int b) {

int temp;

temp = a;
a = b;
b = temp;

printf("After swapping first number is %d and second number is %d", a ,b);

int main(void) {

int first, second;

printf("Enter two numbers : \n");


scanf("%d %d",&first,&second);

swap(first,second);

/* Check whether actual parameters is changed after swapping. */

printf(" \n After swap function called first number is %d and second number is %d", first
,second);

return 0;
}

OUTPUT: -

17
Swapping two number using call by reference: -

#include <stdio.h>
swap (int *, int *);
int main()
{
int a, b;
printf("\nEnter value of a & b: ");
scanf("%d %d", &a, &b);
printf("\nBefore Swapping:\n");
printf("\na = %d\n\nb = %d\n", a, b);
swap(&a, &b);
printf("\nAfter Swapping:\n");
printf("\na = %d\n\nb = %d", a, b);
return 0;
}
swap (int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

OUTPUT: -

18
EXPERIMENT: -7

19
Write a program to implement binary search tree. (Insertion and Deletion in
Binary search Tree).

Insertion: -

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

struct node {
int key;
struct node *left, *right;
};

// A utility function to create a new BST node


struct node* newNode(int item)
{
struct node* temp
= (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

// A utility function to do inorder traversal of BST


void inorder(struct node* root)
{
if (root != NULL) {
inorder(root->left);
printf("%d \n", root->key);
inorder(root->right);
}
}

/* A utility function to insert


a new node with given key in
* BST */
struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL)
return newNode(key);

/* Otherwise, recur down the tree */


if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)

20
node->right = insert(node->right, key);

/* return the (unchanged) node pointer */


return node;
}

// Driver Code
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
struct node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);

// print inoder traversal of the BST


inorder(root);

return 0;
}

OUTPUT: -

Deletion: -
21
#include <stdio.h>
#include <stdlib.h>

struct node {
int key;
struct node *left, *right;
};

// A utility function to create a new BST node


struct node* newNode(int item)
{
struct node* temp
= (struct node*)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

// A utility function to do inorder traversal of BST


void inorder(struct node* root)
{
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}

/* A utility function to
insert a new node with given key in
* BST */
struct node* insert(struct node* node, int key)
{
/* If the tree is empty, return a new node */
if (node == NULL)
return newNode(key);

/* Otherwise, recur down the tree */


if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);

/* return the (unchanged) node pointer */


return node;

22
}

/* Given a non-empty binary search


tree, return the node
with minimum key value found in
that tree. Note that the
entire tree does not need to be searched. */
struct node* minValueNode(struct node* node)
{
struct node* current = node;

/* loop down to find the leftmost leaf */


while (current && current->left != NULL)
current = current->left;

return current;
}

/* Given a binary search tree


and a key, this function
deletes the key and
returns the new root */
struct node* deleteNode(struct node* root, int key)
{
// base case
if (root == NULL)
return root;

// If the key to be deleted


// is smaller than the root's
// key, then it lies in left subtree
if (key < root->key)
root->left = deleteNode(root->left, key);

// If the key to be deleted


// is greater than the root's
// key, then it lies in right subtree
else if (key > root->key)
root->right = deleteNode(root->right, key);

// if key is same as root's key,


// then This is the node
// to be deleted
else {
// node with only one child or no child
if (root->left == NULL) {

23
struct node* temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL) {
struct node* temp = root->left;
free(root);
return temp;
}

// node with two children:


// Get the inorder successor
// (smallest in the right subtree)
struct node* temp = minValueNode(root->right);

// Copy the inorder


// successor's content to this node
root->key = temp->key;

// Delete the inorder successor


root->right = deleteNode(root->right, temp->key);
}
return root;
}

// Driver Code
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
struct node* root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

printf("Inorder traversal of the given tree \n");


inorder(root);

24
printf("\nDelete 20\n");
root = deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n");
inorder(root);

printf("\nDelete 30\n");
root = deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n");
inorder(root);

printf("\nDelete 50\n");
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n");
inorder(root);

return 0;
}

OUTPUT: -

EXPERIMENT: -8

25
Write a program to create a linked list & perform operations such as insert,
delete, update, reverse in the link list.

#include <stdio.h>

// Linked List Node


struct node {
int info;
struct node* link;
};
struct node* start = NULL;

// Function to traverse the linked list


void traverse()
{
struct node* temp;

// List is empty
if (start == NULL)
printf("\nList is empty\n");

// Else print the LL


else {
temp = start;
while (temp != NULL) {
printf("Data = %d\n",
temp->info);
temp = temp->link;
}
}
}

// Function to insert at the front


// of the linked list
void insertAtFront()
{
int data;
struct node* temp;
temp = malloc(sizeof(struct node));
printf("\nEnter number to"
" be inserted :");
scanf("%d", &data);
temp->info = data;

// Pointer of temp will be

26
// assigned to start
temp->link = start;
start = temp;
}

// Function to insert at the end of


// the linked list
void insertAtEnd()
{
int data;
struct node *temp, *head;
temp = malloc(sizeof(struct node));

// Enter the number


printf("\nEnter number to"
" be inserted :");
scanf("%d", &data);

// Changes links
temp->link = 0;
temp->info = data;
head = start;
while (head->link != NULL) {
head = head->link;
}
head->link = temp;
}

// Function to insert at any specified


// position in the linked list
void insertAtPosition()
{
struct node *temp, *newnode;
int pos, data, i = 1;
newnode = malloc(sizeof(struct node));

// Enter the position and data


printf("\nEnter position and data :");
scanf("%d %d", &pos, &data);

// Change Links
temp = start;
newnode->info = data;
newnode->link = 0;
while (i < pos - 1) {
temp = temp->link;

27
i++;
}
newnode->link = temp->link;
temp->link = newnode;
}

// Function to delete from the front


// of the linked list
void deleteFirst()
{
struct node* temp;
if (start == NULL)
printf("\nList is empty\n");
else {
temp = start;
start = start->link;
free(temp);
}
}

// Function to delete from the end


// of the linked list
void deleteEnd()
{
struct node *temp, *prevnode;
if (start == NULL)
printf("\nList is Empty\n");
else {
temp = start;
while (temp->link != 0) {
prevnode = temp;
temp = temp->link;
}
free(temp);
prevnode->link = 0;
}
}

// Function to delete from any specified


// position from the linked list
void deletePosition()
{
struct node *temp, *position;
int i = 1, pos;

// If LL is empty

28
if (start == NULL)
printf("\nList is empty\n");

// Otherwise
else {
printf("\nEnter index : ");

// Position to be deleted
scanf("%d", &pos);
position = malloc(sizeof(struct node));
temp = start;

// Traverse till position


while (i < pos - 1) {
temp = temp->link;
i++;
}

// Change Links
position = temp->link;
temp->link = position->link;

// Free memory
free(position);
}
}

// Function to find the maximum element


// in the linked list
void maximum()
{
int a[10];
int i;
struct node* temp;

// If LL is empty
if (start == NULL)
printf("\nList is empty\n");

// Otherwise
else {
temp = start;
int max = temp->info;

// Traverse LL and update the


// maximum element

29
while (temp != NULL) {

// Update the maximum


// element
if (max < temp->info)
max = temp->info;
temp = temp->link;
}
printf("\nMaximum number "
"is : %d ",
max);
}
}

// Function to find the mean of the


// elements in the linked list
void mean()
{
int a[10];
int i;
struct node* temp;

// If LL is empty
if (start == NULL)
printf("\nList is empty\n");

// Otherwise
else {
temp = start;

// Stores the sum and count of


// element in the LL
int sum = 0, count = 0;
float m;

// Traverse the LL
while (temp != NULL) {

// Update the sum


sum = sum + temp->info;
temp = temp->link;
count++;
}

// Find the mean


m = sum / count;

30
// Print the mean value
printf("\nMean is %f ", m);
}
}

// Function to sort the linked list


// in ascending order
void sort()
{
struct node* current = start;
struct node* index = NULL;
int temp;

// If LL is empty
if (start == NULL) {
return;
}

// Else
else {

// Traverse the LL
while (current != NULL) {
index = current->link;

// Traverse the LL nestedly


// and find the minimum
// element
while (index != NULL) {

// Swap with it the value


// at current
if (current->info > index->info) {
temp = current->info;
current->info = index->info;
index->info = temp;
}
index = index->link;
}

// Update the current


current = current->link;
}
}
}

31
// Function to reverse the linked list
void reverseLL()
{
struct node *t1, *t2, *temp;
t1 = t2 = NULL;

// If LL is empty
if (start == NULL)
printf("List is empty\n");

// Else
else {

// Traverse the LL
while (start != NULL) {

// reversing of points
t2 = start->link;
start->link = t1;
t1 = start;
start = t2;
}
start = t1;

// New head Node


temp = start;

printf("Reversed linked "


"list is :");

// Print the LL
while (temp != NULL) {
printf("%d ", temp->info);
temp = temp->link;
}
}
}

// Driver Code
int main()
{
int choice;
while (1) {

printf("\n\t1 To see list\n");

32
printf("\t2 For insertion at"
" starting\n");
printf("\t3 For insertion at"
" end\n");
printf("\t4 For insertion at "
"any position\n");
printf("\t5 For deletion of "
"first element\n");
printf("\t6 For deletion of "
"last element\n");
printf("\t7 For deletion of "
"element at any position\n");
printf("\t8 To find maximum among"
"the elements\n");
printf("\t9 To find mean of "
"the elements\n");
printf("\t10 To sort element\n");
printf("\t11 To reverse the "
"linked list\n");
printf("\t12 To exit\n");
printf("\nEnter Choice :\n");
scanf("%d", &choice);

switch (choice) {
case 1:
traverse();
break;
case 2:
insertAtFront();
break;
case 3:
insertAtEnd();
break;
case 4:
insertAtPosition();
break;
case 5:
deleteFirst();
break;
case 6:
deleteEnd();
break;
case 7:
deletePosition();
break;
case 8:

33
maximum();
break;
case 9:
mean();
break;
case 10:
sort();
break;
case 11:
reverseLL();
break;
case 12:
exit(1);
break;
default:
printf("Incorrect Choice\n");
}
}
return 0;
}

OUTPUT: -

34
35
36
EXPERIMENT: -9

Write the program for implementation of a file and performing operations


such as insert, delete, update a record in the file.

#include<stdio.h>
struct student
{
int rollno;
char name[30];
float mark;
}stud;
// FUNCTION TO INSERT RECORDS TO THE FILE
void insert()
{
FILE *fp;
fp = fopen("Record", "a");
printf("Enter the Roll no :");
scanf("%d", &[Link]);
printf("Enter the Name :");
scanf("%s", &[Link]);
printf("Enter the mark :");
scanf("%f", &[Link]);
fwrite(&stud, sizeof(stud), 1, fp);
fclose(fp);
}
// FUNCTION TO DISPLAY RECORDS
void disp()
{
FILE *fp1;
fp1 = fopen("Record", "r");
printf("\nRoll Number\tName\tMark\n\n");
while (fread(&stud, sizeof(stud), 1, fp1))
printf(" %d\t\t%s\t%.2f\n", [Link], [Link], [Link]);
fclose(fp1);
}
// FUNCTION TO SEARCH THE GIVEN RECORD
void search()
{
FILE *fp2;
int r, s, avl;
printf("\nEnter the Roll no you want to search :");
scanf("%d", &r);
avl = avlrollno(r);
if (avl == 0)
printf("Roll No %d is not available in the file\n",r);

37
else
{
fp2 = fopen("Record", "r");
while (fread(&stud, sizeof(stud), 1, fp2))
{
s = [Link];
if (s == r)
{
printf("\nRoll no = %d", [Link]);
printf("\nName = %s", [Link]);
printf("\nMark = %.2f\n", [Link]);
}
}
fclose(fp2);
}
}
// FUNCTION TO DELETE A RECORD

void deletefile()
{
FILE *fpo;
FILE *fpt;
int r, s;
printf("Enter the Roll no you want to delete :");
scanf("%d", &r);
if (avlrollno(r) == 0)
printf("Roll no %d is not available in the file\n", r);
else
{
fpo = fopen("Record", "r");
fpt = fopen("TempFile", "w");
while (fread(&stud, sizeof(stud), 1, fpo))
{
s = [Link];
if (s != r)
fwrite(&stud, sizeof(stud), 1, fpt);
}
fclose(fpo);
fclose(fpt);
fpo = fopen("Record", "w");
fpt = fopen("TempFile", "r");
while (fread(&stud, sizeof(stud), 1, fpt))
fwrite(&stud, sizeof(stud), 1, fpo);
printf("\nRECORD DELETED\n");
fclose(fpo);

38
fclose(fpt);
}

}
// FUNCTION TO UPDATE THE RECORD
void update()
{
int avl;
FILE *fpt;
FILE *fpo;
int s, r, ch;
printf("Enter roll number to update:");
scanf("%d", &r);
avl = avlrollno(r);
if (avl == 0)
{
printf("Roll number %d is not Available in the file", r);
}
else
{
fpo = fopen("Record", "r");
fpt = fopen("TempFile", "w");
while (fread(&stud, sizeof(stud), 1, fpo))
{
s = [Link];
if (s != r)
fwrite(&stud, sizeof(stud), 1, fpt);
else
{
printf("\n\t1. Update Name of Roll Number %d", r);
printf("\n\t2. Update Mark of Roll Number %d", r);
printf("\n\t3. Update both Name and Mark of Roll Number %d", r);
printf("\nEnter your choice:");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter Name:");
scanf("%s", &[Link]);
break;
case 2:
printf("Enter Mark : ");
scanf("%f", &[Link]);
break;
case 3:
printf("Enter Name: ");

39
scanf("%s", &[Link]);
printf("Enter Mark: ");
scanf("%f", &[Link]);
break;
default:
printf("Invalid Selection");
break;
}
fwrite(&stud, sizeof(stud), 1, fpt);
}
}
fclose(fpo);
fclose(fpt);
fpo = fopen("Record", "w");
fpt = fopen("TempFile", "r");
while (fread(&stud, sizeof(stud), 1, fpt))
{
fwrite(&stud, sizeof(stud), 1, fpo);
}
fclose(fpo);
fclose(fpt);
printf("RECORD UPDATED");
}
}
/* FUNCTION TO SORT THE RECORD */
void sort()
{
int a[20], count = 0, i, j, t, c;
FILE *fpo;
fpo = fopen("Record", "r");
while (fread(&stud, sizeof(stud), 1, fpo))
{
a[count] = [Link];
count++;
}
c = count;
for (i = 0; i<count - 1; i++)
{
for (j = i + 1; j<count; j++)
{
if (a[i]>a[j])
{
t = a[i];
a[i] = a[j];
a[j] = t;
}

40
}
}
printf("Roll No.\tName\t\tMark\n\n");
count = c;
for (i = 0; i<count; i++)
{
rewind(fpo);
while (fread(&stud, sizeof(stud), 1, fpo))
{
if (a[i] == [Link])
printf("\n %d\t\t %s \t\t %2f",[Link], [Link], [Link]);
}

}
}
// FUNCTION TO CHECK GIVEN ROLL NO IS AVAILABLE //
int avlrollno(int rno)
{
FILE *fp;
int c = 0;
fp = fopen("Record", "r");
while (!feof(fp))
{
fread(&stud, sizeof(stud), 1, fp);

if (rno == [Link])
{
fclose(fp);
return 1;
}
}
fclose(fp);
return 0;
}
//FUNCTION TO CHECK THE FILE IS EMPTY OR NOT
int empty()
{
int c = 0;
FILE *fp;
fp = fopen("Record", "r");
while (fread(&stud, sizeof(stud), 1, fp))
c = 1;
fclose(fp);
return c;
}
// MAIN PROGRAM

41
void main()
{
int c, emp;
do
{
printf("\n\t---Select your choice---------\n");
printf("\n\t1. INSERT\n\t2. DISPLAY\n\t3. SEARCH");
printf("\n\t4. DELETE\n\t5. UPDATE\n\t6. SORT");
printf("\n\t7. EXIT");
printf("\n\n \n");
printf("\nEnter your choice:");
scanf("%d", &c);
printf("\n");
switch (c)
{
case 1:
insert();
break;
case 2:
emp = empty();
if (emp == 0)
printf("\nThe file is EMPTY\n");
else
disp();
break;
case 3:
search();
break;
case 4:
deletefile();
break;
case 5:
update();
break;
case 6:
emp = empty();
if (emp == 0)
printf("\n The file is EMPTY\n");
else
sort();
break;
case 7:
exit(1);
break;
default:
printf("\nYour choice is wrong\nPlease try again. \n");

42
break;

}
} while (c != 7);
}

OUTPUT: -

43
EXPERIMENT: -10

Create a linked list and perform the following operations on it: -


a) Add a node
b) Delete a node

A) Add a node: -

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

// A linked list node


struct Node
{
int data;
struct Node *next;
};

/* Given a reference (pointer to pointer) to the head of a list and


an int, inserts a new node on the front of the list. */
void push(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

/* 2. put in the data */


new_node->data =new_data;

/* 3. Make next of new node as head */


new_node->next = (*head_ref);

/* 4. move the head to point to the new node */


(*head_ref) = new_node;
}

/* Given a node prev_node, insert a new node after the given


prev_node */
void insertAfter(struct Node* prev_node, int new_data)
{
/*1. check if the given prev_node is NULL */
if (prev_node == NULL)
{
printf("the given previous node cannot be NULL");
return;
}

44
/* 2. allocate new node */
struct Node* new_node=(struct Node*) malloc(sizeof(struct Node));

/* 3. put in the data */


new_node->data =new_data;

/* 4. Make next of new node as next of prev_node */


new_node->next = prev_node->next;

/* 5. move the next of prev_node as new_node */


prev_node->next = new_node;
}

/* Given a reference (pointer to pointer) to the head


of a list and an int, appends a new node at the end */
void append(struct Node** head_ref, int new_data)
{
/* 1. allocate node */
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

struct Node *last = *head_ref; /* used in step 5*/

/* 2. put in the data */


new_node->data =new_data;

/* 3. This new node is going to be the last node, so make next of


it as NULL*/
new_node->next = NULL;

/* 4. If the Linked List is empty, then make the new node as head */
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}

/* 5. Else traverse till the last node */


while (last->next != NULL)
last = last->next;

/* 6. Change the next of last node */


last->next = new_node;
return;
}

45
// This function prints contents of linked list starting from head
void printList(struct Node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->next;
}
}

/* Driver program to test above functions*/


int main()
{
/* Start with the empty list */
struct Node* head = NULL;

// Insert 6. So linked list becomes 6->NULL


append(&head, 6);

// Insert 7 at the beginning. So linked list becomes 7->6->NULL


push(&head, 7);

// Insert 1 at the beginning. So linked list becomes 1->7->6->NULL


push(&head, 1);

// Insert 4 at the end. So linked list becomes 1->7->6->4->NULL


append(&head, 4);

// Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL


insertAfter(head->next, 8);

printf("\n Created Linked list is: ");


printList(head);

return 0;
}

OUTPUT: -

46
Delete a node: -

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

// A linked list node


struct Node {
int data;
struct Node* next;
};

/* Given a reference (pointer to pointer) to the head of a


list and an int, inserts a new node on the front of the
list. */
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}

/* Given a reference (pointer to pointer) to the head of a


list and a key, deletes the first occurrence of key in
linked list */
void deleteNode(struct Node** head_ref, int key)
{
// Store head node
struct Node *temp = *head_ref, *prev;

// If head node itself holds the key to be deleted


if (temp != NULL && temp->data == key) {
*head_ref = temp->next; // Changed head
free(temp); // free old head
return;
}

// Search for the key to be deleted, keep track of the


// previous node as we need to change 'prev->next'
while (temp != NULL && temp->data != key) {
prev = temp;
temp = temp->next;
}

// If key was not present in linked list

47
if (temp == NULL)
return;

// Unlink the node from linked list


prev->next = temp->next;

free(temp); // Free memory


}

// This function prints contents of linked list starting


// from the given node
void printList(struct Node* node)
{
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}

// Driver code
int main()
{
/* Start with the empty list */
struct Node* head = NULL;

push(&head, 7);
push(&head, 1);
push(&head, 3);
push(&head, 2);

puts("Created Linked List: ");


printList(head);
deleteNode(&head, 1);
puts("\nLinked List after Deletion of 1: ");
printList(head);
return 0;
}
OUTPUT: -

48

You might also like