Data and Files Structure (MCA-162) Practical File: Bharati Vidyapeeth'S Institute of Computer Applications & Management

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 74

BHARATI VIDYAPEETH’S

INSTITUTE OF COMPUTER APPLICATIONS & MANAGEMENT


(Affiliated to Guru Gobind Singh Indraprastha
University, Approved by AICTE, New Delhi)

Data and Files


Structure
(MCA-162)
Practical File

Submitted To: Submitted By:


Dr. Sunil Pratap Singh Chitra Karakoti (01811604421)
(Associate Professor) MCA 1st Sem, Sec 2
Assignment Set: A (Searching and Sorting in Array)

AP1 Write a program which takes an array of n integers and displays the frequency of
each element present in the array.
#include<stdio.h>
#include<stdlib.h>
void frequency(int *ar, int n){
int i,j,count;
for(i = 0; i < n; i++){
if(ar[i] == -1)
continue;
count = 1;
for(j = i + 1; j < n; j++){
if(ar[i] == ar[j]){
count++;
ar[j] = -1;
}
}
printf("Frequency of %d: %d\n", ar[i], count);
}
getch();
}

int main(){
int n,i;
int *ar;
clrscr();
printf("Input number of elements in array: ");
scanf("%d", &n);
ar = (int*)calloc(n, sizeof(int));
for(i = 0; i < n; i++){
printf("Input ar[%d]: ", i);
scanf("%d", &ar[i]);
}
printf("Entered array is: [");
for(i = 0; i < n; i++){
printf("%d, ", ar[i]);
}
printf("]\n");
frequency(ar, n);
getch();
return 0;
}

AP2 Write a program which takes an array of n integers and performs


searching of an element by implementing linear search and binary search
techniques.

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

int linsearch(int array[], int n, int x)


{
int i;
for (i = 0; i < n; i++)
if (array[i] == x)
return i;
return -1;
}
int binsearch(int array[], int x, int low, int high) {

while (low <= high) {


int mid = low + (high - low) / 2;

if (array[mid] == x)
return mid;

if (array[mid] < x)
low = mid + 1;

else
high = mid - 1;
}

return -1;
}

int main() {
int n = 7;
int result;
int array[] = {2,5,8,10,13,15,18};
int x,ch,i;
clrscr();
for(i=0;i<n;i++)
printf("%d ",array[i]);
printf("\nEnter element to be searched : ");
scanf("%d",&x);
printf("\n1. Linear Search \n2. Binary Search\n");
printf("\nEnter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1 :
result = linsearch(array, n, x);
if(result == -1)
printf("Element not found");
else
printf("Element found at index: %d", result);
getch();
break;
case 2 :
result = binsearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
getch();
break;
}
getch();
return 0;
}

AP3 Write a program which takes an array of n integers and sorts the integers in
descending order using bubble sort and selection sort techniques.

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

void bubbleSort(int array[], int size) {


int step,i;
for (step = 0; step < size - 1; ++step) {
for (i = 0; i < size - step - 1; ++i) {
if (array[i] > array[i + 1]) {
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void selectionSort(int array[], int size) {


int step,i;
for (step = 0; step < size - 1; step++) {
int min_idx = step;
for (i = step + 1; i < size; i++) {
if (array[i] < array[min_idx])
min_idx = i;
}
swap(&array[min_idx], &array[step]);
}
}

void printArray(int array[], int size) {


int i;
for (i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
getch();
}

int main() {
int data[] = {-2, 45, 0, 11, -9};
int size = sizeof(data) / sizeof(data[0]);
int i,ch;
clrscr();
for(i=0;i<size;i++)
printf("%d ",data[i]);

printf("\n1. Bubble Sort \n2. Selection Sort\n");


printf("\nEnter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1 : bubbleSort(data, size);
printf("Sorted Array in Ascending Order using Bubble Sort :\n");
printArray(data, size);
break;
case 2 : selectionSort(data, size);
printf("Sorted array in Acsending Order using Selection Sort :\n");
printArray(data, size);
getch();
break;
}
getch();
return 0;
}
AP4 Write a program which takes an array of n integers and sorts the integers in
ascending order using insertion sort technique.

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

void printArray(int array[], int size) {


int i;
for (i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
getch();
}

void insertionSort(int array[], int size) {


int step;
for (step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;

while (key < array[j] && j >= 0) {


array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}

int main() {

int data[] = {9, 5, 1, 4, 3};


int size = sizeof(data) / sizeof(data[0]);
int i;
clrscr();
printf("\nArray Elements are : ");
printArray(data,size);
insertionSort(data, size);
printf("\n\nSorted array in ascending order:\n");
printArray(data, size);
getch();
return 0;
}

AP5 Write a program which takes an array of n integers and sorts the integers in
ascending order using quick sort technique.

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

void swap(int *a, int *b) {


int t = *a;
*a = *b;
*b = t;
}

int partition(int array[], int low, int high) {


int pivot = array[high];
int j, i = (low - 1);

for (j = low; j < high; j++) {


if (array[j] <= pivot) {
i++;
swap(&array[i], &array[j]);
}
}
swap(&array[i + 1], &array[high]);
return (i + 1);
}

void quickSort(int array[], int low, int high) {


if (low < high) {
int pi = partition(array, low, high);
quickSort(array, low, pi - 1);
quickSort(array, pi + 1, high);
}
}

void printArray(int array[], int size) {


int i;
for (i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
getch();
}

int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};

int n = sizeof(data) / sizeof(data[0]);


clrscr();
printf("Unsorted Array\n");
printArray(data, n);

quickSort(data, 0, n - 1);

printf("Sorted array in ascending order using QUICK SORT: \n");


printArray(data, n);
getch();
return 0;
}
Assignment Set: B (Linked List)

BP1 Write a menu-driven program which implements a linear linked list with following
operations:
a) Insertion of an element at beginning of the list
b) Insertion of an element at specific location of the list
c) Insertion of an element at end of the list
d) Deletion of an element from the beginning of the list
e) Deletion of an element from specific location of the list
f) Deletion of an element from the end of the list
g) Display all elements of the list
h) Search a specific element in the list

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node{
int info;
struct node *link;
};
typedef struct node Node;
Node *head = NULL;

void search(int data)


{
Node *loc=head;
while(loc!=NULL && loc->info!=data)
loc=loc->link;

if(loc==NULL)
printf("Element not found");
else
printf("Element found at %d ", loc);
}

void inbeg(int value)


{
Node *n=(Node*)malloc(sizeof(Node));
n->info=value;
if(head==NULL)
n->link=NULL;
else
{
n->link=head;
}
head=n;
printf("\nNode Added");
}

void inend(int value)


{
Node *ptr=(Node*)malloc(sizeof(Node));
Node *temp;
ptr->info=value;
ptr->link=NULL;
if(head==NULL)
head=ptr;
else
{
temp=head;
while(temp->link!=NULL)
{
temp=temp->link;
}
temp->link=ptr;
printf("\nNode Added");
}
}

void inele(int value)


{
Node *ptr= (Node*)malloc(sizeof(Node));
Node *loc=head;
int data;
printf("\nEnter Element : ");
scanf("%d",&data);
while((loc!=NULL)&&(loc->info!=value))
loc=loc->link;
if(loc==NULL)
printf("No Element");
else
{
ptr->info=data;
ptr->link=loc->link;
loc->link=ptr;
printf("Node Added");
}
}

void delbeg()
{
Node *ptr;
if(head==NULL)
{
printf("Underflow");
}
else
{
ptr=head;
head=head->link;
free(ptr);
printf("Node Deleted from the Beginning.");
}
}

void delend()
{
Node *ptr,*loc;
if(head==NULL)
{
printf("Underflow");
}
ptr=head;
while((ptr->link)->link!=NULL)
ptr=ptr->link;
loc=ptr->link;
ptr->link=NULL;
free(loc);
printf("\nNode deleted from End.");
}

void delele(int item)


{
Node *ptr;
Node *loc=head;
if(head==NULL)
printf("Underflow");
while((loc!=NULL)&&(loc->info!=item))
loc=loc->link;
if(loc==NULL)
printf("No Element Found");
else
{
ptr=loc->link;
loc->link=ptr->link;
printf("\nNode Deleted.");
free(ptr);
}
}

void displaylist()
{
Node *temp=head;
if(head==NULL)
printf("\nUnderflow");
else
{
while(temp!=NULL)
{
printf("%d",temp->info);
printf(" ");
temp=temp->link;
}
}
}

void main()
{
int ch,data,item;
clrscr();
do{
printf("\n**********MENU*************");
printf("\n1. Insertion at beginning");
printf("\n2. Insertion at end");
printf("\n3. Insertion after a given element");
printf("\n4. Deletion at beginning");
printf("\n5. Deletion at end");
printf("\n6. Deletion after a given element");
printf("\n7. Searching");
printf("\n8. Display List");
printf("\n9. Exit");
printf("\nINPUT CHOICE : ");
scanf("%d",&ch);
clrscr();
switch(ch)
{
case 1 : printf("Enter Item to be added : ");
scanf("%d",&item);
inbeg(item);
break;
case 2 : printf("Enter Item to be added : ");
scanf("%d",&item);
inend(item);
getch();
break;
case 3 : printf("Enter after which element node to be added : ");
scanf("%d",&item);
inele(item);
getch();
break;
case 4 : delbeg();
break;
case 5 : delend();
break;
case 6 : printf("Enter Item to be deleted : ");
scanf("%d",&item);
delele(item);
break;
case 7 : printf("Enter element to be searched : ");
scanf("%d",&data);
search(data);
break;
case 8 : displaylist();
break;
case 9 : exit(1);
break;
}
}while(ch!=9);

getch();

}
BP2 A polynomial is composed of different terms where each of them holds a
coefficient and an exponent. Write a program to represent the following
polynomials: 4x4 + 4x3 -2x2 + x and 11x3 + 7x2 - 4x with linear linked list, and then
perform addition of the given polynomials.

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<stdlib.h>
struct node
{

unsigned int coe;


int pow;
struct node *next;
};
typedef struct node NODE;
void createPoly(NODE **);
void printPoly(NODE *);
void addPoly(NODE **, NODE *, NODE *);

void main()
{
NODE *p, *q, *r;
clrscr();
printf("\nCREATE FIRST POLYNOMIAL");
createPoly(&p);
printf("\nFirst Polynomial: ");
printPoly(p);

printf("\nCREATE SECOND POLYNOMIAL");


createPoly(&q);
printf("\nSecond Polynomial: ");
printPoly(q);
printf("\nADDITION OF TWO POLYNOMIAL");
addPoly(&r,p,q);
printPoly(r);

getch();
}

void createPoly(NODE **start)


{
int flag;
int coe, pow;
NODE *node;
node = (NODE *)malloc(sizeof(NODE));
*start = node;
do{
printf("\nInput the Coefficient: ");
scanf("%d", &coe);
printf("\nInput the power: ");
scanf("%d", &pow);
node->coe = coe;
node->pow = pow;
node->next = NULL;
clrscr();
printf("\nDo you want to add more terms to the polynomial: (0/1)");
scanf("%d", &flag);
if(flag)
{
NODE *newNode = (NODE *)malloc(sizeof(NODE));
node->next = newNode;
node = newNode;
node->next = NULL;
}
}while(flag);
}

void printPoly(NODE *node)


{
printf("\nPolynomial Expression");
while(node != NULL)
{
printf("%dx^%d", node->coe, node->pow);
node = node->next;
if(node !=NULL)
{
printf(" + ");
}
}
}

void addPoly(NODE **start, NODE *p, NODE *q)


{
NODE *newNode = (NODE *)malloc(sizeof(NODE));
newNode->next = NULL;
*start = newNode;
while(p && q)
{
if(p->pow > q->pow)
{
newNode->pow = p->pow;
newNode->coe = p->coe;
p = p->next;
}
else if(p->pow < q->pow)
{
newNode->pow = q->pow;
newNode->coe = q->coe;
q = q->next;
}
else
{
newNode->pow = p->pow;
newNode->coe = p->coe + q->coe;
p = p->next;
q = q->next;
}

if(p && q)
{
NODE *node = (NODE *)malloc(sizeof(NODE));
node->next = newNode;
node = newNode;
node->next = NULL;
}
}
while(p || q)
{
NODE *node = (NODE *)malloc(sizeof(NODE));
node->next = newNode;
node = newNode;
node->next = NULL;
if(p)
{
node->pow = p->pow;
node->coe = p->coe;
p = p->next;
}
if(q)
{
node->pow = q->pow;
node->coe = q->coe;
q = q->next;
}
}
}

Assignment Set: C (Stack and Queue)


CP1 Write a menu-driven program which implements a stack (using one- dimensional
array) with following operations:
a) Push (insert an element)
b) Pop (delete an element)
c) Display (print all the elements of stack)

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

int stack[100],choice,n,top,x,i;

void push(void);
void pop(void);
void display(void);

int main()
{
clrscr();
top=-1;
printf("\n Enter the size of STACK [MAX=100] :");
scanf("%d",&n);
do
{
printf("\nSTACK OPERATIONS USING ARRAY");
printf("\n--------------------------------");
printf("\n\1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT");printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
clrscr();
push();
break;
}
case 2:
{
clrscr();
pop();
break;
}
case 3:
{
clrscr();
display();
break;
}
case 4:
{
printf("\nEXITING....");
break;
}
default:
{
printf ("\nPlease Enter a Valid Choice(1/2/3/4)");
}

}
}
while(choice!=4);
getch();
return 0;
}

void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");

}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}

void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}

void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}

CP2 Write a menu-driven program which implements a linear queue (using one-
dimensional array) with following operations:
a) Enqueue (insert an element)
b) Dequeue (delete an element)
c) Display (print all the elements of queue)

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

#define MAX 50

void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
void main()
{
int choice;
clrscr();
do
{
clrscr();
printf(“\n-----MENU-----\n);
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1: insert();
break;
case 2: delete();
getch();
break;
case 3: display();
getch();
break;
case 4: exit(1);
default: printf("Wrong choice \n");
}
}while(choice!=4);
getch();
}

void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
}

void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
}

void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}
CP3 Write a menu-driven program which implements a circular queue (using one-
dimensional array) with following operations:
a) Enqueue (insert an element)
b) Dequeue (delete an element)
c) Display (print all the elements of queue)

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

# define max 6
int queue[max];
int front=-1;
int rear=-1;

void enqueue(int element)


{
if(front==-1 && rear==-1)
{
front=0;
rear=0;
queue[rear]=element;
}
else if((rear+1)%max==front)
{
printf("Queue is overflow..");
}
else
{
rear=(rear+1)%max;
queue[rear]=element;
}
}

int dequeue()
{
if((front==-1) && (rear==-1))
{
printf("\nQueue is underflow..");
}
else if(front==rear)
{
printf("\nThe dequeued element is %d", queue[front]);
front=-1;
rear=-1;
}
else
{
printf("\nThe dequeued element is %d", queue[front]);
front=(front+1)%max;
}
}
void display()
{
int i=front;
if(front==-1 && rear==-1)
{
printf("\n Queue is empty..");
}
else
{
printf("\nElements in a Queue are :");
while(i<=rear)
{
printf("%d,", queue[i]);
i=(i+1)%max;
}
}
}

int main()
{
int ch,x;
clrscr();
do
{
printf("\n Press 1: Insert an element");
printf("\nPress 2: Delete an element");
printf("\nPress 3: Display the element");
printf("\nEnter your choice");
scanf("%d", &ch);

switch(ch)
{

case 1: printf("Enter the element which is to be inserted");


scanf("%d", &x);
enqueue(x);
getch();
break;
case 2: dequeue();
getch();
break;
case 3: display();
getch();
break;
case 4 : printf("\nExiting...");
getch();
return;
default : printf("\nEnter Valid Choice");
break;

}
}while(ch!=4);
getch();
return 0;
}
Assignment Set: D (Tree)

DP1 Write a menu-driven program which implements a binary tree (using

linked list) with following operations:


a) Insertion of a node
b) Deletion of a node
c) Preorder traversal
d) Inorder traversal
e) Postorder traversal
f) Determine total number of leaf nodes

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct node{
int data;
struct node *left;
struct node *right;
};
struct node *root = NULL;
struct node* createNode(int data){
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct queue
{
int front, rear, size;
struct node* *arr;
};
struct queue* createQueue()
{
struct queue* newQueue = (struct queue*) malloc(sizeof( struct queue ));
newQueue->front = -1;
newQueue->rear = 0;
newQueue->size = 0;
newQueue->arr = (struct node**) malloc(100 * sizeof( struct node* ));
return newQueue;
}
void enqueue(struct queue* queue, struct node *temp){
queue->arr[queue->rear++] = temp;
queue->size++;
}
struct node *dequeue(struct queue* queue){
queue->size--;
return queue->arr[++queue->front];
}
void insertNode(int data) {
struct node *newNode = createNode(data);
if(root == NULL){
root = newNode;
return;
}
else {
struct queue* queue = createQueue();
enqueue(queue, root);
while(true) {
struct node *node = dequeue(queue);
if(node->left != NULL && node->right != NULL) {
enqueue(queue, node->left);
enqueue(queue, node->right);
}
else {
if(node->left == NULL) {
node->left = newNode;
enqueue(queue, node->left);
}
else {
node->right = newNode;
enqueue(queue, node->right);
}
break;
}
}
}
}
void inorderTraversal(struct node *node) {
if(root == NULL){
printf("Tree is empty\n");
return;
}
else {
if(node->left != NULL)
inorderTraversal(node->left);
printf("%d ", node->data);
if(node->right != NULL)
inorderTraversal(node->right);
}
}
void preorderTraversal(struct node *node) {
if(root == NULL){
printf("Tree is empty\n");
return;
}
else {
printf("%d ", node->data);
if(node->left != NULL)
inorderTraversal(node->left);
if(node->right != NULL)
inorderTraversal(node->right);
}
}
void postorderTraversal(struct node *node) {
if(root == NULL){
printf("Tree is empty\n");
return;
}
else {
if(node->left != NULL)
inorderTraversal(node->left);
if(node->right != NULL)
inorderTraversal(node->right);
printf("%d ", node->data);
}
}
int main(){
while (1) {
printf("\t1 For insertion \n");
printf("\t2 For deletion \n");
printf("\t3 For traversse -inorder\n");
printf("\t4 For traversse -preorder\n");
printf("\t5 For traversse -postorder\n");
printf("\nEnter Choice :\n");
scanf("%d", &choice);
switch (choice) {
case 1:
insertNode(1);
insertNode(2);
insertNode(3);
insertNode(4);
insertNode(5);
insertNode(6);
insertNode(7);
break;
case 2:
break;
case 3:
printf("\nBinary tree inorder traversal: \n");
inorderTraversal(root);
break;
case 4:
printf("\nBinary tree preorder traversal: \n");
preorderTraversal(root);
break;
case 5:
printf("\nBinary tree postorder traversal: \n");
postorderTraversal(root);
break;
default:
printf("Incorrect Choice\n");
}
}
return 0;
}

DP2 Write a menu-driven program which implements a heap (using one


dimensional array) with following operations:
a) Insertion of a node
b) Deletion of a node
c) Display (print all the elements of heap)

#include <stdio.h>
int size = 0;
void swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
void heapify(int array[], int size, int i)
{
if (size == 1)
{
printf("Single element in the heap");
}
else
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && array[l] > array[largest])
largest = l;
if (r < size && array[r] > array[largest])
largest = r;
if (largest != i)
{
swap(&array[i], &array[largest]);
heapify(array, size, largest);
}
}
}
void insert(int array[], int newNum)
{
if (size == 0)
{
array[0] = newNum;
size += 1;
}
else
{
array[size] = newNum;
size += 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
}
void deleteRoot(int array[], int num)
{
int i;
for (i = 0; i < size; i++)
{
if (num == array[i])
break;
}
swap(&array[i], &array[size - 1]);
size -= 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
void printArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
printf("%d ", array[i]);
printf("\n");
}
int main()
{
int array[10];
insert(array, 3);
insert(array, 4);
insert(array, 9);
insert(array, 5);
insert(array, 2);
printf("Max-Heap array: ");
printArray(array, size);
deleteRoot(array, 4);
printf("After deleting an element: ");
printArray(array, size);
}

DP3 Write a menu-driven program which implements a binary search tree


(using linked list) with following operations:
a) Insertion of a node
b) Deletion of a node
c) Preorder traversal
d) Inorder traversal
e) Postorder traversal

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct node{
int data;
struct node *left;
struct node *right;
};
struct node *root = NULL;
struct node* createNode(int data){
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct queue
{
int front, rear, size;
struct node* *arr;
};
struct queue* createQueue()
{
struct queue* newQueue = (struct queue*) malloc(sizeof( struct queue ));
newQueue->front = -1;
newQueue->rear = 0;
newQueue->size = 0;
newQueue->arr = (struct node**) malloc(100 * sizeof( struct node* ));
return newQueue;
}
void enqueue(struct queue* queue, struct node *temp){
queue->arr[queue->rear++] = temp;
queue->size++;
}
struct node *dequeue(struct queue* queue){
queue->size--;
return queue->arr[++queue->front];
}
void insertNode(int data) {
struct node *newNode = createNode(data);
if(root == NULL){
root = newNode;
return;
}
else {
struct queue* queue = createQueue();
enqueue(queue, root);
while(true) {
struct node *node = dequeue(queue);
if(node->left != NULL && node->right != NULL) {
enqueue(queue, node->left);
enqueue(queue, node->right);
}
else {
if(node->left == NULL) {
node->left = newNode;
enqueue(queue, node->left);
}
else {
node->right = newNode;
enqueue(queue, node->right);
}
break;
}
}
}
}
void inorderTraversal(struct node *node) {
if(root == NULL){
printf("Tree is empty\n");
return;
}
else {
if(node->left != NULL)
inorderTraversal(node->left);
printf("%d ", node->data);
if(node->right != NULL)
inorderTraversal(node->right);
}
}
void preorderTraversal(struct node *node) {
if(root == NULL){
printf("Tree is empty\n");
return;
}
else {
printf("%d ", node->data);
if(node->left != NULL)
inorderTraversal(node->left);
if(node->right != NULL)
inorderTraversal(node->right);
}
}
void postorderTraversal(struct node *node) {
if(root == NULL){
printf("Tree is empty\n");
return;
}
else {
if(node->left != NULL)
inorderTraversal(node->left);
if(node->right != NULL)
inorderTraversal(node->right);
printf("%d ", node->data);
}
}
int main(){
int choice;
while (1) {
printf("\t1 For insertion \n");
printf("\t2 For deletion \n");
printf("\t3 For traversse -inorder\n");
printf("\t4 For traversse -preorder\n");
printf("\t5 For traversse -postorder\n");
printf("\nEnter Choice :\n");
scanf("%d", &choice);
switch (choice) {
case 1:
insertNode(1);
insertNode(2);
insertNode(3);
insertNode(4);
insertNode(5);
insertNode(6);
insertNode(7);
break;
case 2:
break;
case 3:
printf("\nBinary tree inorder traversal: \n");
inorderTraversal(root);
break;
case 4:
printf("\nBinary tree preorder traversal: \n");
preorderTraversal(root);
break;
case 5:
printf("\nBinary tree postorder traversal: \n");
postorderTraversal(root);
break;
default:
printf("Incorrect Choice\n");
}
}
return 0;
}

DP4 Write a program which takes an array of n integers and sorts the
integers in ascending order using heap sort technique.

#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int n;
int arr[n];
printf("\nEnter Size of array :\n");
scanf("%d", &n);
printf("\n enter element of array \n");
for(int i = 0; i < n; ++i) {
scanf("%d", &arr[i]);
}
heapSort(arr, n);
printf("Sorted array is given in the following way \n");
printArray(arr, n);
return 0;
}

Assignment Set: E (Graph)

EP1 Write a menu-driven program which implements a graph (using


adjacency matrix) with following operations:
a) Insertion of a vertex
b) Insertion of an edge
c) Deletion of a vertex
d) Deletion of an edge
e) Calculation of degree of each vertex
f) Calculation of number of self-loops in the graph

#include<stdio.h>
#include<stdlib.h>
struct Edge;
struct Vertex
{
int info;
struct Vertex *nextVertex;
struct Edge *firstEdge;
}*start = NULL;
struct Edge
{
struct Vertex *destVertex;
struct Edge *nextEdge;
};
struct Vertex *findVertex(int u);
void insertVertex(int u);
void insertEdge(int u,int v);
void deleteEdge(int u,int v);
void deleteIncomingEdges(int u);
void deleteVertex(int u);
void display();
void insertVertex(int u)
{
struct Vertex *ptr;
struct Vertex *tmp = (struct Vertex *)malloc(sizeof(struct Vertex));
tmp->info = u;
tmp->nextVertex = NULL;
tmp->firstEdge = NULL;
if(start == NULL)
{
start = tmp;
return;
}
ptr = start;
while(ptr->nextVertex!=NULL)
ptr = ptr->nextVertex;
ptr->nextVertex = tmp;
}
void deleteVertex(int u)
{
struct Vertex *tmp,*q;
struct Edge *p,*temporary;
if(start == NULL)
{
printf("\nNo vertices to be deleted\n");
return;
}
if(start->info == u)
{
tmp = start;
start = start->nextVertex;
}
else
{
q = start;
while(q->nextVertex != NULL)
{
if(q->nextVertex->info == u)
break;
q = q->nextVertex;
}
if(q->nextVertex==NULL)
{
printf("Vertex not found\n");
return;
}
else
{
tmp = q->nextVertex;
q->nextVertex = tmp->nextVertex;
}
}
p = tmp->firstEdge;
while(p!=NULL)
{
temporary = p;
p = p->nextEdge;
free(temporary);
}
free(tmp);
}
void deleteIncomingEdges(int u)
{
struct Vertex *ptr;
struct Edge *q,*tmp;
ptr = start;
while(ptr!=NULL)
{
if(ptr->firstEdge == NULL)
{
ptr = ptr->nextVertex;
continue;
}
if(ptr->firstEdge->destVertex->info == u)
{
tmp = ptr->firstEdge;
ptr->firstEdge = ptr->firstEdge->nextEdge;
free(tmp);
continue;
}
q = ptr->firstEdge;
while(q->nextEdge!= NULL)
{ if(q->nextEdge->destVertex->info == u)
{
tmp = q->nextEdge;
q->nextEdge = tmp->nextEdge;
free(tmp);
continue;
}
q = q->nextEdge;
}
ptr = ptr->nextVertex;
}
}
struct Vertex *findVertex(int u)
{
struct Vertex *ptr,*loc;
ptr = start;
while(ptr!=NULL)
{
if(ptr->info == u )
{
loc = ptr;
return loc;
}
else
ptr = ptr->nextVertex;
}
loc = NULL;
return loc;
}
void insertEdge(int u,int v)
{
struct Vertex *locu,*locv;
struct Edge *ptr,*tmp;
locu = findVertex(u);
locv = findVertex(v);
if(locu == NULL )
{
printf("\nStart vertex not present, first insert vertex %d\n",u);
return;
}
if(locv == NULL )
{
printf("\nEnd vertex not present, first insert vertex %d\n",v);
return;
}
tmp =(struct Edge *) malloc(sizeof(struct Edge));
tmp->destVertex = locv;
tmp->nextEdge = NULL;
if(locu->firstEdge == NULL)
{
locu->firstEdge = tmp;
return;
}
ptr = locu->firstEdge;
while(ptr->nextEdge!=NULL)
ptr = ptr->nextEdge;
ptr->nextEdge = tmp;
}
void deleteEdge(int u,int v)
{
struct Vertex *locu;
struct Edge *tmp,*q;
locu = findVertex(u);
if(locu == NULL )
{
printf("\nStart vertex not present\n");
return;
}
if(locu->firstEdge == NULL)
{
printf("\nEdge not present\n");
return;
}
if(locu->firstEdge->destVertex->info == v)
{
tmp = locu->firstEdge;
locu->firstEdge = locu->firstEdge->nextEdge;
free(tmp);
return;
}
q = locu->firstEdge;
while(q->nextEdge != NULL)
{
if(q->nextEdge->destVertex->info == v)
{
tmp = q->nextEdge;
q->nextEdge = tmp->nextEdge;
free(tmp);
return;
}
q = q->nextEdge;
}
printf("\nThis Edge not present in the graph\n");
}
void display()
{
struct Vertex *ptr;
struct Edge *q;
ptr = start;
while(ptr!=NULL)
{
printf("%d ->",ptr->info);
q = ptr->firstEdge;
while(q!=NULL)
{
printf(" %d",q->destVertex->info);
q = q->nextEdge;
}
printf("\n");
ptr = ptr->nextVertex;
}
}
int main()
{
int choice,u,origin,destin;
while(1)
{
printf("\n1.Insert a Vertex\n");
printf("2.Insert an Edge\n");
printf("3.Delete a Vertex\n");
printf("4.Delete an Edge\n");
printf("5.Display\n");
printf("6.Exit\n");
printf("\nEnter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter a vertex to be inserted : ");
scanf("%d",&u);
insertVertex(u);
break;
case 2:
printf("\nEnter an Edge to be inserted : ");
scanf("%d %d",&origin,&destin);
insertEdge(origin,destin);
break;
case 3:
printf("\nEnter a vertex to be deleted : ");
scanf("%d",&u);
deleteIncomingEdges(u);
deleteVertex(u);
break;
case 4:
printf("\nEnter an edge to be deleted : ");
scanf("%d %d",&origin,&destin);
deleteEdge(origin,destin);
break;
case 5:
display();
break;
case 6:
exit(1);
default:
printf("\nWrong choice\n");
break;
}
}
return 0;
}

EP2 Write a program to traverse the following graph using breadth first
search and depth first search techniques.

#include <stdio.h>
#include <stdlib.h>
#define SIZE 40
struct node {
int vertex;
struct node* next;
};
struct node* createNode(int v);
struct queue {
int items[SIZE];
int front;
int rear;
};
struct queue* createQueue();
void enqueue(struct queue* q, int);
int dequeue(struct queue* q);
void display(struct queue* q);
int isEmpty(struct queue* q);
void printQueue(struct queue* q);
struct queue* createQueue() {
struct queue* q = (struct queue *)malloc(sizeof(struct queue));
q->front = -1;
q->rear = -1;
return q;
}
int isEmpty(struct queue* q) {
if (q->rear == -1)
return 1;
else
return 0;
}
void enqueue(struct queue* q, int value) {
if (q->rear == SIZE - 1)
printf("\nQueue is Full!!");
else {
if (q->front == -1)
q->front = 0;
q->rear++;
q->items[q->rear] = value;
}
}
int dequeue(struct queue* q) {
int item;
if (isEmpty(q)) {
printf("Queue is empty");
item = -1;
} else {
item = q->items[q->front];
q->front++;
if (q->front > q->rear) {
printf("Resetting queue ");
q->front = q->rear = -1;
}
}
return item;
}
void printQueue(struct queue* q) {
int i = q->front;
if (isEmpty(q)) {
printf("Queue is empty");
} else {
printf("\nQueue contains \n");
for (i = q->front; i < q->rear + 1; i++) {
printf("%d ", q->items[i]);
}
}
}
struct node* createNode(int);
struct Graph {
int numVertices;
struct node** adjLists;
int* visited;
};
struct node* createNode(int v) {
struct node* newNode = (struct node *)malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int vertices) {
struct Graph* graph =(struct Graph *) malloc(sizeof(struct Graph));
graph->numVertices = vertices;
graph->adjLists = (struct node **)malloc(vertices * sizeof(struct node*));
graph->visited = (int *)malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) {
graph->adjLists[i] = NULL;
graph->visited[i] = 0;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}
void printGraph(struct Graph* graph) {
int v;
for (v = 0; v < graph->numVertices; v++) {
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp) {
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}
void DFS(struct Graph* graph, int vertex) {
struct node* adjList = graph->adjLists[vertex];
struct node* temp = adjList;
graph->visited[vertex] = 1;
printf("%d ", &vertex);
while (temp != NULL) {
int connectedVertex = temp->vertex;
if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}
void bfs(struct Graph* graph, int startVertex) {
struct queue* q = createQueue();
graph->visited[startVertex] = 1;
enqueue(q, startVertex);
while (!isEmpty(q)) {
printQueue(q);
int currentVertex = dequeue(q);
printf("%d ", &currentVertex);
struct node* temp = graph->adjLists[currentVertex];
while (temp) {
int adjVertex = temp->vertex;
if (graph->visited[adjVertex] == 0) {
graph->visited[adjVertex] = 1;
enqueue(q, adjVertex);
}
temp = temp->next;
}
}
}
int main() {
struct Graph* graph = createGraph(4);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 2);
addEdge(graph, 2, 3);
printf("\n graph:- \n");
printGraph(graph);
printf("\n DFS Traversal \n");
DFS(graph, 2);
printf("\n BFS Traversal \n");
bfs(graph,2);
return 0;
}

EP3 Write a program to determine shortest path from a to f (using


Dijkstra’s algorithm) in the following graph.

#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX],int n,int startnode)
{
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}
for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}

EP4 Write a program to determine shortest paths between every pair


of vertices (using Floyd Warshell’s algorithm) in the following graph.
#include <stdio.h>
#define nV 6
#define INF 999
void printMatrix(int matrix[][nV]);
void floydWarshall(int graph[][nV]) {
int matrix[nV][nV], i, j, k;
for (i = 0; i < nV; i++)
for (j = 0; j < nV; j++)
matrix[i][j] = graph[i][j];
for (k = 0; k < nV; k++) {
for (i = 0; i < nV; i++) {
for (j = 0; j < nV; j++) {
if (matrix[i][k] + matrix[k][j] < matrix[i][j])
matrix[i][j] = matrix[i][k] + matrix[k][j];
}
}
}
printMatrix(matrix);
}
void printMatrix(int matrix[][nV]) {
for (int i = 0; i < nV; i++) {
for (int j = 0; j < nV; j++) {
if (matrix[i][j] == INF)
printf("%4s", "INF");
else
printf("%4d", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int graph[nV][nV] = {{INF, 3, 9, INF,INF,INF},
{3,INF,8,11,9,INF},
{9, 8,INF,1,INF,2},
{INF,9,1, INF,6,9},
{INF, 11,INF,6,INF,7},
{INF, INF, 2, 9,7,INF}};
printf("\n floyd warshall algorithm \n");
floydWarshall(graph);
}

Assignment Set: F (File Handling)

FP1 Write a program that generates n random integers and stores them
in a text file, named as “All.txt”. Then, retrieve the stored integers from
this file and copy to “Odd.txt” and „Even.txt‟ based upon the type of
number, i.e. if the retrieved integer is odd number then store in
“Odd.txt” file or if the retrieved integer is even then store in “Even.txt”
file. Finally, display the contents of all three files.

#include <stdio.h>
#include <conio.h>
int main()
{
FILE *f1, *f2, *f3;
int number, i;
printf("Input the contents of DATA File\n");
f1 = fopen("DATA", "w");
for (i = 1; i <= 9; i++)
{
scanf("%d", &number);
putw(number, f1);
}
fclose(f1);
f1 = fopen("DATA", "r");
f2 = fopen("ODD", "w");
f3 = fopen("EVEN", "w");
while ((number = getw(f1)) != EOF)
{
if (number % 2 == 0)
{
putw(number, f3);
}
else
{
putw(number, f2);
}
}
fclose(f1);
fclose(f2);
fclose(f3);
f2 = fopen("ODD", "r");
f3 = fopen("EVEN", "r");
printf("\n\nContents of ODD File\n\n");
while ((number = getw(f2)) != EOF)
printf("%4d", number);
printf("\n\nContents of EVEN File\n\n");
while ((number = getw(f3)) != EOF)
printf("%4d", number);
fclose(f2);
fclose(f3);
return 0;
}

FP2 A text file contains student‟s grade, followed by student‟s name.


Sample data is following:
8.3 Gautam
9.4 Jasleen
6.7 Gaurav
9.4 Naman
5.7 Ishika
7.5 Rakesh
Write a program to find the highest grade, and list all the students who
have highest grade. Also, list the details of students ‟having 3rd highest
grade”.

#include <stdio.h>
#include <conio.h>
int main()
{
FILE *fp;
long n;
char c;
fp = fopen("RANDOM", "w");
while ((c = getchar()) != EOF)
{
putc(c, fp);
}
printf("No. of Characters Entered = %1d\n", ftell(fp));
fclose(fp);
fp = fopen("RANDOM", "r");
n = 0;
while (feof(fp) == 0)
{
fseek(fp, -1, 2);
printf("position of %c is %1d\n", getc(fp), ftell(fp));
n = n - 1;
}
return 0;
}

FP3 Write a program to implement 20 integers (with some duplicate


integers) in a hash table (with separate chaining for collision
resolution).

#include <stdio.h>
#include <stdlib.h>
struct set
{
int key;
int data;
};
struct set *array;
int capacity = 10;
int size = 0;
int hashFunction(int key)
{
return (key % capacity);
}
int checkPrime(int n)
{
int i;
if (n == 1 || n == 0)
{
return 0;
}
for (i = 2; i < n / 2; i++)
{
if (n % i == 0)
{
return 0;
}
}
return 1;
}
int getPrime(int n)
{
if (n % 2 == 0)
{
n++;
}
while (!checkPrime(n))
{
n += 2;
}
return n;
}
void init_array()
{
capacity = getPrime(capacity);
array = (struct set *)malloc(capacity * sizeof(struct set));
for (int i = 0; i < capacity; i++)
{
array[i].key = 0;
array[i].data = 0;
}
}
void insert(int key, int data)
{
int index = hashFunction(key);
if (array[index].data == 0)
{
array[index].key = key;
array[index].data = data;
size++;
printf("\n Key (%d) has been inserted \n", key);
}
else if (array[index].key == key)
{
array[index].data = data;
}
else
{
printf("\n Collision occured \n");
}
}
void remove_element(int key)
{
int index = hashFunction(key);
if (array[index].data == 0)
{
printf("\n This key does not exist \n");
}
else
{
array[index].key = 0;
array[index].data = 0;
size--;
printf("\n Key (%d) has been removed \n", key);
}
}
void display()
{
int i;
for (i = 0; i < capacity; i++)
{
if (array[i].data == 0)
{
printf("\n array[%d]: / ", i);
}
else
{
printf("\n key: %d array[%d]: %d \t", array[i].key, i, array[i].data);
}
}
}
int size_of_hashtable()
{
return size;
}
int main()
{
int choice, key, data, n;
int c = 0;
init_array();
do
{
printf("1.Insert item in the Hash Table"
"\n2.Remove item from the Hash Table"
"\n3.Check the size of Hash Table"
"\n4.Display a Hash Table"
"\n\n Please enter your choice: ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("Enter key -:\t");
scanf("%d", &key);
printf("Enter data -:\t");
scanf("%d", &data);
insert(key, data);
break;
case 2:
printf("Enter the key to delete-:");
scanf("%d", &key);
remove_element(key);
break;
case 3:
n = size_of_hashtable();
printf("Size of Hash Table is-:%d\n", n);
break;
case 4:
display();
break;
default:
printf("Invalid Input\n");
}
printf("\nDo you want to continue (press 1 for yes): ");
scanf("%d", &c);
} while (c == 1);
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy