0% found this document useful (0 votes)
11 views81 pages

DS PracticalSlipsSolution

The document contains multiple C programming tasks, including creating a Binary Search Tree, evaluating a polynomial using an array, reversing a string using a static stack, creating a circular doubly linked list, finding the union of two singly linked lists, converting an adjacency matrix to an adjacency list, and counting nodes in a singly linked list. Each task includes code snippets demonstrating the implementation of the respective data structures and algorithms. The programs are designed to be menu-driven or to perform specific operations based on user input.

Uploaded by

shraddhavinod1
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)
11 views81 pages

DS PracticalSlipsSolution

The document contains multiple C programming tasks, including creating a Binary Search Tree, evaluating a polynomial using an array, reversing a string using a static stack, creating a circular doubly linked list, finding the union of two singly linked lists, converting an adjacency matrix to an adjacency list, and counting nodes in a singly linked list. Each task includes code snippets demonstrating the implementation of the respective data structures and algorithms. The programs are designed to be menu-driven or to perform specific operations based on user input.

Uploaded by

shraddhavinod1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

1)Write menu driven program using ‘C’ for Binary Search Tree.

The menu includes


- Create a Binary Search Tree
- Insert element in a Binary Search Tree
Display

#include <stdio.h>
#include <stdlib.h>
struct BST
{

int data;
struct BST *left;
struct BST *right;

};

typedef struct BST NODE;


NODE *node;
NODE* createtree(NODE *node, int data)

if (node == NULL)
{

NODE *temp;
temp= (NODE*)malloc(sizeof(NODE));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}

if (data < (node->data))


{
node->left = createtree(node->left, data);
}

else if (data > node->data)


{
node -> right = createtree(node->right, data);
}
return node;

void inorder(NODE *node)


{

if(node != NULL)
{
inorder(node->left);
printf("%d\t", node->data);
inorder(node->right);
}
}

void preorder(NODE *node)


{

if(node != NULL)
{
printf("%d\t", node->data);
preorder(node->left);
preorder(node->right);
}
}

void postorder(NODE *node)


{

if(node != NULL)
{
postorder(node->left);
postorder(node->right);
printf("%d\t", node->data);
}
}

int main()
{
int data, ch, i, n;
NODE *root=NULL;
while (ch!=5)
{
printf("\n\n1.Insertion in Binary Search Tree");
printf("\n2.Inorder");
printf("\n3.Preorder");
printf("\n4.Postorder");
printf("\n5.Exit\n");
printf("\nEnter your Choice: ");

scanf("%d", &ch);

switch (ch)
{
case 1: printf("\nEnter size of tree: " );
scanf("%d", &n);
printf("\nEnter the elements of tree)\n");

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


{
scanf("%d", &data);
root=createtree(root, data);
}
break;

case 2: printf("\nInorder Traversal: \n");


inorder(root);
break;

case 3: printf("\nPreorder Traversal: \n");


preorder(root);
break;

case 4: printf("\nPostorder Traversal: \n");


postorder(root);
break;

case 5: exit(0);

default: printf("\nEnter valid choice\n");


break;

}
}
}

2) Write a ‘C’ program to evaluate a given polynomial using function. (Use


array).

#include <stdio.h>
#include <math.h>

int evaluate (int arr[],int limit,int x)


{
int sum =0, count;

for (count=limit; count>=0; count--)


{
sum=sum+arr[count]*pow (x, count);
}
return sum;
}

int main ()
{
int array[30], degree, x, count, result, i;

printf("\n Enter the Degree of polynomial :");


scanf("%d",&degree);

printf("\n Enter the Co-efficient of polynomial:");


for(count=degree;count>=0;count--)
{
printf("\n Co-efficient of count :" );
scanf("%d",&array[count]);
}

printf("\n The Polynomial :");


for(i=degree ;i>0; i--)
{
if (array[i] !=0)
{
printf("%d^%d+",array[i],i);
}
}
printf("%d",array[count]);
printf("\n Enter the value of x :");
scanf("%d",&x);

result = evaluate (array, degree, x);


printf("\n Evaluate of polynomial :%d",result);
return 0;
}

3) Write a ‘C’ program to accept a string from user and reverse it using
Static implementation of Stack.

#include <stdio.h>
#include <string.h>

#define max 50
int top,stack[max];

void push(char x){

// Push(Inserting Element in stack) operation


if(top == max-1){
printf("stack overflow");
} else {
stack[++top]=x;
}

void pop(){
// Pop (Removing element from stack)
printf("%c",stack[top--]);
}

main()
{
char str[]="India";
int len = strlen(str);
int i;

for(i=0;i<len;i++)
push(str[i]);
for(i=0;i<len;i++)
pop();
}

4) Write a ‘C’ program to create Circularly Doubly Linked list and display
it

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

struct node {
int num;
struct node * nextptr;
}*stnode;

void ClListcreation(int n);


void displayClList();

int main()
{
int n;
stnode = NULL;
printf("\n\n Circular Linked List : Create and display a circular linked list
:\n");
printf("-----------------------------------------------------------------------\n");

printf(" Input the number of nodes : ");


scanf("%d", &n);

ClListcreation(n);
displayClList();
return 0;
}

void ClListcreation(int n)
{
int i, num;
struct node *preptr, *newnode;

if(n >= 1)
{
stnode = (struct node *)malloc(sizeof(struct node));

printf(" Input data for node 1 : ");


scanf("%d", &num);
stnode->num = num;
stnode->nextptr = NULL;
preptr = stnode;
for(i=2; i<=n; i++)
{
newnode = (struct node *)malloc(sizeof(struct node));
printf(" Input data for node %d : ", i);
scanf("%d", &num);
newnode->num = num;
newnode->nextptr = NULL; // next address of new node set as NULL
preptr->nextptr = newnode; // previous node is linking with new node
preptr = newnode; // previous node is advanced
}
preptr->nextptr = stnode; //last node is linking with first node
}
}

void displayClList()
{
struct node *tmp;
int n = 1;

if(stnode == NULL)
{
printf(" No data found in the List yet.");
}
else
{
tmp = stnode;
printf("\n\n Data entered in the list are :\n");

do {
printf(" Data %d = %d\n", n, tmp->num);

tmp = tmp->nextptr;
n++;
}while(tmp != stnode);
}
}

5)Write a program to create two singly linked list of elements of type integer
and find the union of the linked lists. (Accept elements in the sorted order)

#include<stdio.h>
struct node
{
int data;
struct node *next;
};
typedef struct node NODE;
NODE *alloc(int);
NODE *create();
NODE *findlast(NODE *);
NODE *unionlist(NODE *,NODE *);
NODE *search(NODE *,int);
void display(NODE *);
NODE *getnode();
void main()
{
NODE *list1=NULL,*list2=NULL,*list3=NULL;
clrscr();
printf(“\nCreate first list.”);
list1=create();
printf(“\nCreate second list.”);
list2=create();
printf(“\n Data in first list: “);
display(list1);
printf(“\n Data in second list: “);
display(list2);
printf(“\n\n Union of two list is: “);
list3=unionlist(list1,list2);
if(list3==NULL)
printf(“\nList of union is empty”);
else
display(list3);
getch();
}
NODE *alloc(int val)
{
NODE *temp;
temp=(NODE *)malloc(sizeof(NODE));
temp->data=val;
temp->next=NULL;
return temp;
}
NODE *getnode()
{
NODE *temp;
temp=(NODE *)malloc(sizeof(NODE));
printf(“\nEnter the data: “);
scanf(“%d”,&temp->data);
temp->next=NULL;
return temp;
}
NODE *search(NODE *list,int val)
{
NODE *ptr;
for(ptr=list;ptr!=NULL && ptr->data!=val;ptr=ptr->next);
return(ptr);
}
NODE *create()
{
NODE *ptr,*temp,*list=NULL;
int n,i;
printf(“\n Enter how many nodes : “);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
temp=getnode();
if(list==NULL)
{
list=temp;
}
else
{
ptr=findlast(list);
ptr->next=temp;
}
}
return(list);
}
NODE *findlast(NODE *list)
{
NODE *ptr;
for(ptr=list;ptr->next!=NULL;ptr=ptr->next);
return(ptr);
}
NODE *unionlist(NODE *list1,NODE *list2)
{
NODE *temp,*ptr1,*ptr2,*list3=NULL;
int i,val;
for(ptr1=list1;ptr1!=NULL;ptr1=ptr1->next)
{
temp=alloc(ptr1->data);
if(list3==NULL)
list3=temp;
else
{
ptr2=findlast(list3);
ptr2->next=temp;
}
}
for(ptr1=list2;ptr1!=NULL;ptr1=ptr1->next)
{
ptr2=search(list1,ptr1->data);
if(ptr2==NULL)
{
temp=alloc(ptr1->data);

ptr2=findlast(list3);
ptr2->next=temp;
}
}
return(list3);
}
void display(NODE *list)
{
NODE *ptr;
for(ptr=list;ptr!=NULL;ptr=ptr->next)
printf(“%d->”,ptr->data);
printf(“NULL”);
}
6) Write a ‘C’ program to read the adjacency matrix of directed graph and
convert it into an adjacency list.

#include <stdio.h>
// N vertices and M 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


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
createAdjMatrix(Adj, arr);

// Print Adjacency Matrix


printAdjMatrix(Adj);

return 0;
}

7)Write menu driven program using ‘C’ for Binary Search Tree. The
menu includes
- Create a Binary Search Tree
- Traverse it by using Inorder and Postorder traversing technique

#include <stdio.h>
#include <stdlib.h>
struct BST
{

int data;
struct BST *left;
struct BST *right;

};

typedef struct BST NODE;


NODE *node;
NODE* createtree(NODE *node, int data)

if (node == NULL)
{

NODE *temp;
temp= (NODE*)malloc(sizeof(NODE));
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}

if (data < (node->data))


{
node->left = createtree(node->left, data);
}

else if (data > node->data)


{
node -> right = createtree(node->right, data);
}

return node;

void inorder(NODE *node)


{
if(node != NULL)
{
inorder(node->left);
printf("%d\t", node->data);
inorder(node->right);
}
}

void preorder(NODE *node)


{

if(node != NULL)
{
printf("%d\t", node->data);
preorder(node->left);
preorder(node->right);
}
}

void postorder(NODE *node)


{

if(node != NULL)
{
postorder(node->left);
postorder(node->right);
printf("%d\t", node->data);
}
}

int main()
{
int data, ch, i, n;
NODE *root=NULL;
while (ch!=5)
{
printf("\n\n1.Insertion in Binary Search Tree");
printf("\n2.Inorder");
printf("\n3.Preorder");
printf("\n4.Postorder");
printf("\n5.Exit\n");
printf("\nEnter your Choice: ");

scanf("%d", &ch);

switch (ch)
{
case 1: printf("\nEnter size of tree: " );
scanf("%d", &n);
printf("\nEnter the elements of tree)\n");

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


{
scanf("%d", &data);
root=createtree(root, data);
}
break;

case 2: printf("\nInorder Traversal: \n");


inorder(root);
break;

case 3: printf("\nPreorder Traversal: \n");


preorder(root);
break;

case 4: printf("\nPostorder Traversal: \n");


postorder(root);
break;

case 5: exit(0);

default: printf("\nEnter valid choice\n");


break;

}
}
}

8)Write a ‘C’ program to create a singly linked list and count total number
of nodes in it and display the list and total number of Nodes.

#include <stdio.h>
#include <stdlib.h>
// Structure for a node in a linked list
struct node {
int num; // Data of the node
struct node *nextptr; // Address of the next node
} *stnode; // Pointer to the starting node

// Function prototypes
void createNodeList(int n); // Function to create the linked list
int NodeCount(); // Function to count the nodes
void displayList(); // Function to display the linked list

// Main function
int main() {
int n, totalNode;

// Displaying the purpose of the program


printf("\n\n Linked List : Create a singly linked list and count the number of
nodes :\n");
printf("------------------------------------------------------------------------------\n");

// Inputting the number of nodes for the linked list


printf(" Input the number of nodes : ");
scanf("%d", &n);

// Creating the linked list with n nodes


createNodeList(n);
printf("\n Data entered in the list are : \n");

// Displaying the data entered in the linked list


displayList();

// Counting the number of nodes in the linked list


totalNode = NodeCount();
printf("\n Total number of nodes = %d\n", totalNode);

return 0;
}

// Function to create a linked list with n nodes


void createNodeList(int n) {
struct node *fnNode, *tmp;
int num, i;
// Allocating memory for the starting node
stnode = (struct node *)malloc(sizeof(struct node));

// Checking if memory allocation is successful


if(stnode == NULL) {
printf(" Memory can not be allocated.");
} else {
// Reading data for the starting node from user input
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode->num = num;
stnode->nextptr = NULL; // Setting the next pointer to NULL
tmp = stnode;

// Creating n nodes and adding them to the linked list


for(i = 2; i <= n; i++) {
fnNode = (struct node *)malloc(sizeof(struct node));

// Checking if memory allocation is successful


if(fnNode == NULL) {
printf(" Memory can not be allocated.");
break;
} else {
// Reading data for each node from user input
printf(" Input data for node %d : ", i);
scanf(" %d", &num);

fnNode->num = num; // Setting the data for fnNode


fnNode->nextptr = NULL; // Setting the next pointer to NULL

tmp->nextptr = fnNode; // Linking the current node to fnNode


tmp = tmp->nextptr; // Moving tmp to the next node
}
}
}
}

// Function to count the number of nodes in the linked list


int NodeCount() {
int ctr = 0;
struct node *tmp;
tmp = stnode;
// Counting the nodes by traversing the linked list
while(tmp != NULL) {
ctr++;
tmp = tmp->nextptr;
}
return ctr;
}

// Function to display the linked list


void displayList() {
struct node *tmp;
if(stnode == NULL) {
printf(" No data found in the list.");
} else {
tmp = stnode;
while(tmp != NULL) {
printf(" Data = %d\n", tmp->num); // Printing the data of current node
tmp = tmp->nextptr; // Advancing the position of current node
}
}
}

9) Write a ‘C’ program to accept and sort n elements in ascending order by using
bubble sort.

#include <stdio.h>
#define MAXSIZE 10

void main()
{
int array[MAXSIZE];
int i, j, num, temp;

printf("Enter the value of num \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");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
}

10) Write a ‘C’ program to accept and sort n elements in ascending order
by 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;
}

11) Write a program to accept a postfix expression and evaluate the


expression using the stack.
Example: Input: ab+cd-* Values: a=4, b=2, c=5, d=3 Answer: 12

#include<stdio.h>
int stack[20];
int top = -1;

void push(int x)
{
stack[++top] = x;
}

int pop()
{
return stack[top--];
}

int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;
}
12) Write a ‘C’ program to create a singly linked list, reverse it and
display both the list.

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

// Structure for a node in a linked list


struct node {
int num; // Data of the node
struct node *nextptr; // Address of the next node
} *stnode; // Pointer to the starting node

// Function prototypes
void createNodeList(int n); // Function to create the linked list
void reverseDispList(); // Function to reverse the linked list
void displayList(); // Function to display the linked list

// Main function
int main() {
int n;

// Displaying the purpose of the program


printf("\n\n Linked List : Create a singly linked list and print it in reverse
order :\n");
printf("------------------------------------------------------------------------------\n");

// Inputting the number of nodes for the linked list


printf(" Input the number of nodes : ");
scanf("%d", &n);

// Creating the linked list with n nodes


createNodeList(n);
printf("\n Data entered in the list are : \n");

// Displaying the data entered in the linked list


displayList();

// Reversing the linked list


reverseDispList();
printf("\n The list in reverse are : \n");

// Displaying the reversed linked list


displayList();
return 0;
}

// Function to create a linked list with n nodes


void createNodeList(int n) {
struct node *fnNode, *tmp;
int num, i;

// Allocating memory for the starting node


stnode = (struct node *)malloc(sizeof(struct node));

// Checking if memory allocation is successful


if(stnode == NULL) {
printf(" Memory can not be allocated.");
} else {
// Reading data for the starting node from user input
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode->num = num;
stnode->nextptr = NULL; // Setting the next pointer to NULL
tmp = stnode;

// Creating n nodes and adding them to the linked list


for(i = 2; i <= n; i++) {
fnNode = (struct node *)malloc(sizeof(struct node));

// Checking if memory allocation is successful


if(fnNode == NULL) {
printf(" Memory can not be allocated.");
break;
} else {
// Reading data for each node from user input
printf(" Input data for node %d : ", i);
scanf(" %d", &num);

fnNode->num = num; // Setting the data for fnNode


fnNode->nextptr = NULL; // Setting the next pointer to NULL

tmp->nextptr = fnNode; // Linking the current node to fnNode


tmp = tmp->nextptr; // Moving tmp to the next node
}
}
}
}

// Function to reverse the linked list


void reverseDispList() {
struct node *prevNode, *curNode;

if(stnode != NULL) {
prevNode = stnode;
curNode = stnode->nextptr;
stnode = stnode->nextptr;

prevNode->nextptr = NULL; // Convert the first node as last

while(stnode != NULL) {
stnode = stnode->nextptr;
curNode->nextptr = prevNode;

prevNode = curNode;
curNode = stnode;
}
stnode = prevNode; // Convert the last node as head
}
}

// Function to display the linked list


void displayList() {
struct node *tmp;
if(stnode == NULL) {
printf(" No data found in the list.");
} else {
tmp = stnode;
while(tmp != NULL) {
printf(" Data = %d\n", tmp->num); // Prints the data of current node
tmp = tmp->nextptr; // Advances the position of current node
}
}
}
13) Write a ‘C’ program to read ‘n’ integers and store them in a Binary
search tree and display the nodes level wise.

C program to demonstrate insert operation in binary search tree


#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)
node->right = insert(node->right, key);
/* return the (unchanged) node pointer */
return node;
}
// Driver Program to test above functions
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;
}

14) Write a ‘C’ program to sort randomly generated array elements using
Insertion sort method. (Use Random Function)

#include <math.h>
#include <stdio.h>

void insertionSort(int arr[], int N) {

// Starting from the second element


for (int i = 1; i < N; i++) {
int key = arr[i];
int j = i - 1;

// Move elements of arr[0..i-1], that are


// greater than key, to one position to
// the right of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
// Move the key to its correct position
arr[j + 1] = key;
}
}

int main() {
int arr[] = { 12, 11, 13, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);

printf("Unsorted array: ");


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

// Calling insertion sort on array arr


insertionSort(arr, N);

printf("Sorted array: ");


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

return 0;
}

15) Write a menu driven program using ‘C’ for singly linked list-
- To create linked list.
- To display linked list
- To search node in linked list.
- Insert at last position

// C program for the all operations in


// the Singly Linked List

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

// Linked List Node


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

// Function to create list with n nodes initially


void createList()
{
if (start == NULL) {
int n;
printf("\nEnter the number of nodes: ");
scanf("%d", &n);
if (n != 0) {
int data;
struct node* newnode;
struct node* temp;
newnode = malloc(sizeof(struct node));
newnode->link = NULL;
start = newnode;
temp = start;
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
start->info = data;

for (int i = 2; i <= n; i++) {


newnode = malloc(sizeof(struct node));
newnode->link = NULL;
temp->link = newnode;
printf("\nEnter number to"
" be inserted : ");
scanf("%d", &data);
newnode->info = data;
temp = temp->link;
}
}
printf("\nThe list is created\n");
}
else
printf("\nThe list is already created\n");
}

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


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

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

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

// Function to search an element in linked list


void search()
{
int found = -1;
// creating node to traverse
struct node* tr = start;

// first checking if the list is empty or not


if (start == NULL) {
printf("Linked list is empty\n");
}
else {
printf("\nEnter the element you want to search: ");
int key;
scanf("%d", &key);

// checking by traversing
while (tr != NULL) {
// checking for key
if (tr->info == key) {
found = 1;
break;
}
// moving forward if not at this position
else {
tr = tr->link;
}
}

// printing found or not


if (found == 1) {
printf(
"Yes, %d is present in the linked list.\n",
key);
}
else {
printf("No, %d is not present in the linked "
"list.\n",
key);
}
}
}

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

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


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 Search an element in linked list\n");
printf("\t13 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:
maximum();
break;
case 9:
mean();
break;
case 10:
sort();
break;
case 11:
reverseLL();
break;
case 12:
search();
break;
case 13:
exit(1);
break;
default:
printf("Incorrect Choice\n");
}
}
return 0;
}

16) Write a menu driven program using ‘C’ for Dynamic implementation
of Queue for integers. The menu includes
- Insert
- Delete
- Display
- Exit

#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct node
{
int data;
struct node *link;
}*front, *rear;

// function protypes
void insert();
void delete();
void queue_size();
void check();
void first_element();

void main()
{
int choice, value;

while(1)
{
printf("enter the choice \n");
printf("1 : create an empty queue \n2 : Insert element\n");
printf("3 : Dequeue an element \n4 : Check if empty\n");
printf("5. Get the first element of the queue\n");
printf("6. Get the number of entries in the queue\n");
printf("7. Exit\n");
scanf("%d", &choice);
switch (choice) // menu driven program
{
case 1:
printf("Empty queue is created with a capacity of %d\n", MAX);
break;
case 2:
insert();
break;
case 3:
delete();
break;
case 4:
check();
break;
case 5:
first_element();
break;
case 6:
queue_size();
break;
case 7:
exit(0);
default:
printf("wrong choice\n");
break;
}
}
}

// to insert elements in queue


void insert()
{
struct node *temp;

temp = (struct node*)malloc(sizeof(struct node));


printf("Enter value to be inserted \n");
scanf("%d", &temp->data);
temp->link = NULL;
if (rear == NULL)
{
front = rear = temp;
}
else
{
rear->link = temp;
rear = temp;
}
}

// delete elements from queue


void delete()
{
struct node *temp;

temp = front;
if (front == NULL)
{
printf("queue is empty \n");
front = rear = NULL;
}
else
{
printf("deleted element is %d\n", front->data);
front = front->link;
free(temp);
}
}

// check if queue is empty or not


void check()
{
if (front == NULL)
printf("\nQueue is empty\n");
else
printf("*************** Elements are present in the queue
**************\n");
}

// returns first element of queue


void first_element()
{
if (front == NULL)
{
printf("**************** The queue is empty ****************\n");
}
else
printf("**************** The front element is %d ***********\n",
front->data);
}

// returns number of entries and displays the elements in queue


void queue_size()
{
struct node *temp;

temp = front;
int cnt = 0;
if (front == NULL)
{
printf(" queue empty \n");
}
while (temp)
{
printf("%d ", temp->data);
temp = temp->link;
cnt++;
}
printf("********* size of queue is %d ******** \n", cnt);
}

16) Write a C program that accepts the graph as an adjacency matrix and
checks if the graph is undirected. The matrix for undirected graph is
symmetric. Also calculate in degree of all vertices
- Read a graph as adjacency Matrix
- Check the matrix is symmetric or not
- Calculate indegree of all vertices

// C program for the above approach


#include <stdio.h>

// N vertices and M 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


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
createAdjMatrix(Adj, arr);
// Print Adjacency Matrix
printAdjMatrix(Adj);

return 0;
}

17) Write a ‘C’ program to accept and sort n elements in ascending order
using Selection sort method.

#include <stdio.h>

void selectionSort(int arr[], int N) {

// Start with the whole array as unsored and one by


// one move boundary of unsorted subarray towards right
for (int i = 0; i < N - 1; i++) {

// Find the minimum element in unsorted array


int min_idx = i;
for (int j = i + 1; j < N; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}

// Swap the found minimum element with the first


// element in the unsorted part
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

int main() {
int arr[] = {64, 25, 12, 22, 11};
int N = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: \n");
for (int i = 0; i < N; i++) {
printf("%d ", arr[i]);
}
printf("\n");

// Calling selection sort


selectionSort(arr, N);

printf("Sorted array: \n");


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

18) Write a C program to accept an infix expression and convert it into


postfix form.(Use Static Implementation of Stack)
Example: - A * B + C as AB*C+

#include<stdio.h>
#include<ctype.h>

char stack[100];
int top = -1;

void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}

int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;

while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c ",pop());
push(*e);
}
e++;
}

while(top != -1)
{
printf("%c ",pop());
}return 0;
}

19) Write a ‘C’ program to create doubly link list and display nodes having
odd value

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

// Structure for a doubly linked list node


struct node {
int num;
struct node *preptr;
struct node *nextptr;
} *stnode, *ennode;

// Function prototypes
void DlListcreation(int n);
void displayDlList();

int main() {
int n;
stnode = NULL;
ennode = NULL;
printf("\n\n Doubly Linked List: Create and display a doubly linked list:\n");
printf("-------------------------------------------------------------------\n");

printf(" Input the number of nodes : ");


scanf("%d", &n);

DlListcreation(n); // Create a doubly linked list


displayDlList(); // Display the created doubly linked list
return 0;
}

// Function to create a doubly linked list


void DlListcreation(int n) {
int i, num;
struct node *fnNode;

if (n >= 1) {
stnode = (struct node *)malloc(sizeof(struct node)); // Allocate memory for
the first node

if (stnode != NULL) {
printf(" Input data for node 1 : ");
scanf("%d", &num);

stnode->num = num;
stnode->preptr = NULL;
stnode->nextptr = NULL;
ennode = stnode; // Assign stnode as the last node
// Create nodes and link them to form the doubly linked list
for (i = 2; i <= n; i++) {
fnNode = (struct node *)malloc(sizeof(struct node));
if (fnNode != NULL) {
printf(" Input data for node %d : ", i);
scanf("%d", &num);
fnNode->num = num;
fnNode->preptr = ennode;
fnNode->nextptr = NULL;

ennode->nextptr = fnNode;
ennode = fnNode;
} else {
printf(" Memory can not be allocated.");
break;
}
}
} else {
printf(" Memory can not be allocated.");
}
}
}

// Function to display the doubly linked list


void displayDlList() {
struct node *tmp;
int n = 1;
if (stnode == NULL) {
printf(" No data found in the List yet.");
} else {
tmp = stnode;
printf("\n\n Data entered on the list are :\n");

// Traverse and display each node's data in the list


while (tmp != NULL) {
printf(" node %d : %d\n", n, tmp->num);
n++;
tmp = tmp->nextptr; // Move to the next node
}
}
}
20) Write a ‘C’ program to accept a string from user and reverse it using
Dynamic implementation of Stack.

#include <stdio.h>
#include <string.h>

#define max 50
int top,stack[max];

void push(char x){

// Push(Inserting Element in stack) operation


if(top == max-1){
printf("stack overflow");
} else {
stack[++top]=x;
}

void pop(){
// Pop (Removing element from stack)
printf("%c",stack[top--]);
}

int main()
{
char str[]="India";
int len = strlen(str);
int i;

for(i=0;i<len;i++)
push(str[i]);

for(i=0;i<len;i++)
pop();
return 0;
}
21) Write a ‘C’ program to accept names from the user and sort in
alphabetical order using bubble sort
- Accept n name
- Bubble sort Function
- Display
#include <stdio.h>
#include <string.h>
void main()
{

char name[10][8], tname[10][8], temp[8];


int i, j, n;

printf("Enter the value of n \n");


scanf("%d", &n);
printf("Enter %d names n \n", n);

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


{
scanf("%s", name[i]);
strcpy(tname[i], name[i]);
}

for (i = 0; i < n - 1 ; i++)


{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}

printf("\n----------------------------------------\n");
printf("Input NamestSorted names\n");
printf("------------------------------------------\n");

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


{
printf("%s\t\t%s\n", tname[i], name[i]);
}

printf("------------------------------------------\n");

22)Write menu driven program using ‘C’ for Dynamic implementation of


Stack. The menu includes following operations:
- Push
- Pop
- Display
- Exit

#include<stdio.h>
#include<stdlib.h>
#define max_size 5
int stack[max_size],top=-1;
/*------ Function Prototype------------*/
void push();
void pop();
void peep();
void display();
/*-------------------------------------*/
int main()
{
int choice;
do
{
//printf("\n");
printf("\n\n--------STACK OPERATIONS-----------\n");
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Peep\n");
printf("4.Display\n");
printf("5.Exit\n");
printf("-----------------------");
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peep();
break;
case 4:
display();
break;
case 5:
exit(0);
break;
default:
printf("\nInvalid choice:\n");
break;
}
}while(choice!=5);
return 0;
}
void push() //Inserting element in to the stack
{
int item;
if(top==(max_size-1))
{
printf("\nStack Overflow:");
}
else
{
printf("Enter the element to be inserted:\t");
scanf("%d",&item);
top=top+1;
stack[top]=item;
}
}
void pop() //deleting an element from the stack
{
int item;
if(top==-1)
{
printf("Stack Underflow:");
}
else
{
item=stack[top];
top=top-1;
printf("\nThe poped element: %d\t",item);
}
}
void peep()
{
if(top==-1)
{
printf("\nStack is empty:");
}
else
{
printf("The topmost element of the stack is %d",stack[top]);
}
}
void display()
{
int i;
if(top==-1)
{
printf("\nStack is Empty:");
}
else
{
printf("\nThe stack elements are:\n" );
for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
}
}

23) Write a ‘C’ program to create to a Singly linked list. Accept the
number from user, search the number in the list.If the number is present
display the Position of node .If number not present print the message
“Number not Found”.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node* head=NULL;

struct node *cn()


{
struct node* n;
n=(struct node *)malloc(sizeof(struct node));
return(n);
}

void createnode(int n) //Function to create Linked list.


{
int i,x;
struct node * temp,*newnode;
printf("Enter elements of linked list :\n");
for(i=1;i<=n;i++)
{
scanf("%d",&x);
if(head==NULL) //checking in linked list is empty
{
head=cn();
head->data=x;
head->next=NULL;
temp=head;
}
else
{
newnode=cn();
newnode->data=x;
newnode->next=NULL;
temp->next=newnode;
temp=newnode;
}
}
}

void display() //Function to traverse Linked list.


{
struct node * temp;
temp=head;
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}

void search(int key) //Function to delete a node from Linked list.


{
struct node * temp;
int i=1,flag=0;
temp=head;
if(head==NULL)
{
printf("Linked list is empty. \n");
}
else
{
while(temp!=NULL)
{
if(key==temp->data)
{
flag=1;
break;
}
temp=temp->next;
i++;

}
if(flag==0)
{
printf("Elemet not found.\n");

}
else
{
printf("Element found at position :%d",i);
}
}

void main()
{
int n,key;
printf("Enter size of Linked list :\n");
scanf("%d",&n);
createnode(n);
printf("\n\nLinked List :\n");
display();
printf("\nEnter element you want to search :\n");
scanf("%d",&key);
search(key);
}

24) Write a ‘C’ program to read a postfix expression, evaluate it and


display the result. (Use Static Implementation of Stack).

#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
// Stack implementation
int stack[MAX_SIZE];
int top = -1;
void push(int item) {
if (top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
top++;
stack[top] = item;
}
int pop() {
if (top < 0) {
printf("Stack Underflow\n");
return -1;
}
int item = stack[top];
top--;
return item;
}
int is_operator(char symbol) {
if (symbol == '+' || symbol == '-' || symbol == '*' || symbol == '/') {
return 1;
}
return 0;
}
int evaluate(char* expression) {
int i = 0;
char symbol = expression[i];
int operand1, operand2, result;

while (symbol != '\0') {


if (symbol >= '0' && symbol <= '9') {
int num = symbol - '0';
push(num);
}
else if (is_operator(symbol)) {
operand2 = pop();
operand1 = pop();
switch(symbol) {
case '+': result = operand1 + operand2; break;
case '-': result = operand1 - operand2; break;
case '*': result = operand1 * operand2; break;
case '/': result = operand1 / operand2; break;
}
push(result);
}
i++;
symbol = expression[i];
}
result = pop();
return result;
}

int main() {
char expression[] = "5 6 7 + * 8 -";
int result = evaluate(expression);
printf("Result= %d\n", result);
return 0;
}

25) Write a ‘C’ program to accept the names of cities and store them in
array. Accept the city name from user and use linear search algorithm to
check whether the city is present in array or not.

#include<stdio.h>
#include<string.h>
typedef struct city
{
char name[30];
int code;
}record;
record city[100];
int read_file(record *a)
{
int i=0;
FILE *fp;
if((fp=fopen("sortedcities.txt","r"))!=NULL)
while(!feof(fp))
{
fscanf(fp,"%s%d",a[i].name,&a[i].code);
i++;
}
return (i-1);
}
void write_file(record *a,int n)
{
int i=0;
FILE *fp;
if((fp=fopen("sorted_cities.txt","w"))!=NULL)
for(i=0;i<n;i++)
fprintf(fp,"\n%s\t%d",a[i].name,a[i].code);
}
void sort(record *a,int n)
{
int i,j;
record t;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(strcmp(a[j].name,a[j+1].name)>0)
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
int read_file1(record *a)
{
int i=0;
FILE *fp;
if((fp=fopen("sorted_cities.txt","r"))!=NULL)
while(!feof(fp))
{
fscanf(fp,"%s%d",a[i].name,&a[i].code);
i++;
}
return (i-1);
}
void b_search(record *a,int n,char key[20])
{
int l,h,mid;
l=0;
h=n-1;
while(h>=l)
{
mid=(l+h)/2;
if(strcmp(key,a[mid].name)==0)
{
printf("\nSTD code:%d\n ",a[mid].code);
break;
}
else if(strcmp(key,a[mid].name)<0)
h=mid-1;
else
l=mid+1;
}
if(h<l)
printf("\ncity not in list\n");
}
int main()
{
char key[20];
int n,m;
n=read_file(city);
sort(city,n);
write_file(city,n);
printf("\nenter city name\n");
scanf("%s",key);
b_search(city,n,key);
return 0;
}
26) Write a ‘C’ program to read ‘n’ integers and store them in a binary
Search tree structure and count the following and display it.
- Number of nodes
- Degree of tree
- Leaf nodes

#include <stdio.h>
#include <stdlib.h>
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);
/* Sample Tree 1:
* 25
* / \
* 27 19
* /\ /\
* 17 91 13 55
*/
printf("Number of nodes in tree 1 = %d ",countnodes(newnode));
printf("\n");
count = 0;

/* Creating second Tree. */


struct node *node = createnode(1);
node->right = createnode(2);
node->right->right = createnode(3);
node->right->right->right = createnode(4);
node->right->right->right->right = createnode(5);
/* Sample Tree 2: Right Skewed Tree (Unbalanced).
* 1
* \
* 2
* \
* 3
* \
* 4
* \
* 5
*/
printf("Number of nodes in tree 2 = %d ",countnodes(node));
printf("\n");
count = 0;

/* Creating third Tree. */


struct node *root = createnode(15);
/* Sample Tree 3- Tree having just one root node.
* 15
*/
printf("Number of nodes in tree 3 = %d",countnodes(root));
return 0;
}
27) Write a ‘C’ program to accept and sort n elements in ascending order
using Merge sort method.

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

// merge function
void Merge(int arr[], int left, int mid, int right)
{
int i, j, k;
int size1 = mid - left + 1;
int size2 = right - mid;

// created temporary array


int Left[size1], Right[size2];

// copying the data from arr to temporary array


for (i = 0; i < size1; i++)
Left[i] = arr[left + i];

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


Right[j] = arr[mid + 1 + j];

// merging of the array


i = 0; // intital index of first subarray
j = 0; // inital index of second subarray
k = left; // initial index of parent array
while (i < size1 && j < size2)
{
if (Left[i] <= Right[j])
{
arr[k] = Left[i];
i++;
}
else
{
arr[k] = Right[j];
j++;
}
k++;
}

// copying the elements from Left[], if any


while (i < size1)
{
arr[k] = Left[i];
i++;
k++;
}

// copying the elements from Right[], if any


while (j < size2)
{
arr[k] = Right[j];
j++;
k++;
}
}

//merge sort function


void Merge_Sort(int arr[], int left, int right)
{
if (left < right)
{

int mid = left + (right - left) / 2;

// recursive calling of merge_sort


Merge_Sort(arr, left, mid);
Merge_Sort(arr, mid + 1, right);

Merge(arr, left, mid, right);


}
}

// driver code
int main()
{
int size;
printf("Enter the size: ");
scanf("%d", &size);

int arr[size];
printf("Enter the elements of array: ");
for (int i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}

Merge_Sort(arr, 0, size - 1);

printf("The sorted array is: ");


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

28) Write a ‘C’ program to create a singly Link list and display its
alternative nodes. (start displaying from first node)

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

struct node
{
int a;
struct node *next;
};

void generate(struct node **);


void display(struct node *);
void delete(struct node **);

int main()
{
struct node *head = NULL;

generate(&head);
printf("\nDisplaying the alternate nodes\n");
display(head);
delete(&head);

return 0;
}

void display(struct node *head)


{
static flag = 0;
if(head != NULL)
{
if (!(flag % 2))
{
printf("%d ", head->a);
}
flag++;
display(head->next);
}
}

void generate(struct node **head)


{
int num, i;
struct node *temp;

printf("Enter length of list: ");


scanf("%d", &num);
for (i = num; i > 0; i--)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->a = i;
if (*head == NULL)
{
*head = temp;
(*head)->next = NULL;
}
else
{
temp->next = *head;
*head = temp;
}
}
}

void delete(struct node **head)


{
struct node *temp;
while (*head != NULL)
{
temp = *head;
*head = (*head)->next;
free(temp);
}
}

29) Write a ‘C’ program which accept the string and check whether the
string is Palindrome or not using stack. (Use Static/Dynamic
implementation of Stack)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
int top = -1, front = 0;
int stack[MAX];
void push(char);
void pop();
/* push a character into stack */
void push(char a)
{
top++;
stack[top] = a;
}
/* delete an element in stack */
void pop()
{
top--;
}
int main()
{
int i, cho;
char s[MAX], b;
printf("\tMENU");
printf("\n---------------------------\n");
printf("1.Check string is palindrome.\n2.Exit\n");
printf("---------------------------\n");
while (1)
{
printf("Choose operation : ");
scanf("%d", &cho);
switch (cho)
{
case 1:
printf("\nEnter string : ");
scanf("%s", s);
for (i = 0;s[i] != '\0';i++)
{
b = s[i];
push(b);
}
for (i = 0;i < (strlen(s) / 2);i++)
{
if (stack[top] == stack[front])
{
pop();
front++;
}
else
{
printf("'%s' is not palindrome.\n\n", s);
break;
}
}
if ((strlen(s) / 2)== front)
printf("'%s' is palindrome.\n\n", s);
front = 0;
top = -1;
break;
case 2:
exit(0);
default: printf("Invalid operation \n");
}
}
return 0;
}

30) Write a ‘C’ program to swap mth and nth element of singly linked list

#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *link;
}*head,*q,*temp,*t;
int cnt,num1,num2,m,n;
void create();
void display();
void swap();
int count();
void main()
{
int ch='y';
clrscr();
while(ch=='y'||ch=='Y')
{
create();
printf("\nWant to add another node(Y|N): ");
scanf("%s",&ch);
}
display();
swap();
count();
display();
getch();
}
void create()
{
temp=malloc(sizeof(struct node));
printf("\nEnter the elements for singly linked list: ");
scanf("%d",&temp->data);
temp->link=NULL;
if(head==NULL)
head=temp;
else
{
q=head;
while(q->link!=NULL)
{
q=q->link;
}
q->link=temp;
}
}
void display()
{
if(head==NULL)
printf("\nlinked list is empty");
else
{
printf("\nElement in singly linked list are: \n");
q=head;
while(q!=NULL)
{
printf("%d\n",q->data);
q=q->link;
}
}
}
void swap()
{
int i;
printf("\nEnter Mth and Nth position of singly linked list for swaping: ");
scanf("\n%d%d",&m,&n);
count();
if(m>0&&m<=cnt&&n>0&&n<=cnt)
{
q=head;
i=0;
printf("\n\nElement after swapping");
while(q!=NULL)
{
i++;
if(m==i)
q->data=num2;
if(n==i)
q->data=num1;
q=q->link;
}

else
printf("\nyou entered wrong position please try again");
}
int count()
{
cnt=0;
q=head;
while(q!=NULL)
{
cnt++;
if(cnt==m)
num1=q->data;
if(cnt==n)
num2=q->data;
q=q->link;
}
return cnt;
}

31) Write a ‘C’ program to read an adjacency matrix of a directed graph


and traverse using BFS
#include <stdio.h>

int n, i, j, visited[10], queue[10], front = -1, rear = -1;


int adj[10][10];

void bfs(int v)
{
for (i = 1; i <= n; i++)
if (adj[v][i] && !visited[i])
queue[++rear] = i;
if (front <= rear)
{
visited[queue[front]] = 1;
bfs(queue[front++]);
}
}

int main()
{
int v;
printf("Enter the number of vertices: ");
scanf("%d", &n);
for (i = 1; i <= n; i++)
{
queue[i] = 0;
visited[i] = 0;
}
printf("Enter graph data in matrix form: \n");
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
scanf("%d", &adj[i][j]);
printf("Enter the starting vertex: ");
scanf("%d", &v);
bfs(v);
printf("The node which are reachable are: \n");
for (i = 1; i <= n; i++)
if (visited[i])
printf("%d\t", i);
else
printf("BFS is not possible. Not all nodes are reachable");
return 0;
}

32) Write a ‘C’ program Accept n elements from user store it in an array.
Accept a value from the user and use linear/Sequential search method to
check whether the value is present in array or not. Display proper message.

#include <stdio.h>

int linearSearch(int* arr, int n, int key) {

// Starting the loop and looking for the key in arr


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

// If key is found, return key


if (arr[i] == key) {
return i;
}
}

// If key is not found, return some value to indicate


// end
return -1;
}

int main() {
int arr[] = { 10, 50, 30, 70, 80, 60, 20, 90, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;

// Calling linearSearch() for arr with key = 43


int i = linearSearch(arr, n, key);

// printing result based on value returned by


// linearSearch()
if (i == -1)
printf("Key Not Found");
else
printf("Key Found at Index: %d", i);

return 0;
}

33) Write a ‘C’ program which accept an Expression and check whether
the expression is Parenthesized or not using stack. (Use Static/Dynamic
implementation of Stack).

#include<stdio.h>
int main()
{
char expression[50]; // declaration of char type array
int x=0, i=0; // declaration of two integer type variables
printf("\nEnter an expression");
scanf("%s", expression);
// Scanning the expression until we reach the end of the expression.
while(expression[i]!= '\0')
{
// Condition to check the symbol is '('
if(expression[i]=='(')
{
x++; // incrementing 'x' variable
}
// condition to check the symbol is ')'
else if(expression[i]==')')
{
x--; // decrementing 'x' variable
if(x<0)
break;
}
i++; // incrementing 'i' variable.
}
// Condition to check whether x is equal to 0 or not.
if(x==0)
{
printf("Expression is balanced");
}

else
{
printf("Expression is unbalanced");
}
return 0;
}

34) Write a ‘C’ program to remove last node of the singly linked list and
insert it at the beginning of list.
#include<stdio.h>
#include<stdlib.h>

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

void deleteEnd (struct Node **head)


{
struct Node *temp = *head;
struct Node *previous;

// if there are no nodes in Linked List can't delete


if (*head == NULL)
{
printf ("Linked List Empty, nothing to delete");
return;
}

// if Linked List has only 1 node


if (temp->next == NULL)
{
printf ("%d deleted\n", (*head)->data);
*head = NULL;
return;
}

// else traverse to the last node


while (temp->next != NULL)
{
// store previous link node as we need to change its next val
previous = temp;
temp = temp->next;
}
// Curr assign 2nd last node's next to Null
previous->next = NULL;
// delete the last node
printf ("%d deleted\n", temp->data);
free (temp);
// 2nd last now becomes the last node
}

void display (struct Node *node)


{

// as linked list will end when Node is Null


while (node != NULL)
{
printf ("%d ", node->data);
node = node->next;
}
printf ("\n\n");
}

int main ()
{
//creating 4 pointers of type struct Node
//So these can point to address of struct type variable
struct Node *head = NULL;
struct Node *node2 = NULL;
struct Node *node3 = NULL;
struct Node *node4 = NULL;
struct Node *node5 = NULL;
struct Node *node6 = NULL;

// allocate 3 nodes in the heap


head = (struct Node *) malloc (sizeof (struct Node));
node2 = (struct Node *) malloc (sizeof (struct Node));
node3 = (struct Node *) malloc (sizeof (struct Node));
node4 = (struct Node *) malloc (sizeof (struct Node));
node5 = (struct Node *) malloc (sizeof (struct Node));
node6 = (struct Node *) malloc (sizeof (struct Node));

head->data = 2; // data set for head node


head->next = node2; // next pointer assigned to address of node2
node2->data = 4;
node2->next = node3;

node3->data = 6;
node3->next = node4;

node4->data = 8;
node4->next = node5;

node5->data = 10;
node5->next = node6;

node6->data = 12;
node6->next = NULL;

printf ("Linked list: ");


display (head);

deleteEnd (&head);
deleteEnd (&head);

printf ("\nLinked list: ");


display (head);

return 0;
}

35) Implement Static implementation of circular queue of integers with


following operation:
- Initialize(),insert(), delete(), isempty(), isfull(), display()

// Circular Queue implementation in C

#include <stdio.h>

#define SIZE 5

int items[SIZE];
int front = -1, rear = -1;

// check if the queue is full


int isFull() {
if ((front == (rear + 1) % SIZE) || (front == 0 && rear == SIZE - 1)) return 1;
return 0;
}

// check if the queue is empty


int isEmpty() {
if (front == -1) return 1;
return 0;
}

// adding an element
void enQueue(int element) {
if (isFull())
printf("\n Queue is full!! \n");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
items[rear] = element;
printf("\n Inserted -> %d", element);
}
}

// removing an element
int deQueue() {
int element;
if (isEmpty()) {
printf("\n Queue is empty !! \n");
return (-1);
} else {
element = items[front];
if (front == rear) {
front = -1;
rear = -1;
}
// Q has only one element, so we reset the
// queue after dequeing it. ?
else {
front = (front + 1) % SIZE;
}
printf("\n Deleted element -> %d \n", element);
return (element);
}
}
// display the queue
void display() {
int i;
if (isEmpty())
printf(" \n Empty Queue\n");
else {
printf("\n Front -> %d ", front);
printf("\n Items -> ");
for (i = front; i != rear; i = (i + 1) % SIZE) {
printf("%d ", items[i]);
}
printf("%d ", items[i]);
printf("\n Rear -> %d \n", rear);
}
}

int main() {
// fails because front = -1
deQueue();

enQueue(1);
enQueue(2);
enQueue(3);
enQueue(4);
enQueue(5);

// fails to enqueue because front == 0 && rear == SIZE - 1


enQueue(6);

display();
deQueue();

display();

enQueue(7);
display();

// fails to enqueue because front == rear + 1


enQueue(8);

return 0;
}
36) Write a ‘C’ program to create Doubly Link list and display it.

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

// Structure for a doubly linked list node


struct node {
int num;
struct node *preptr;
struct node *nextptr;
} *stnode, *ennode;

// Function prototypes
void DlListcreation(int n);
void displayDlList();

int main() {
int n;
stnode = NULL;
ennode = NULL;
printf("\n\n Doubly Linked List: Create and display a doubly linked list:\n");
printf("-------------------------------------------------------------------\n");

printf(" Input the number of nodes : ");


scanf("%d", &n);

DlListcreation(n); // Create a doubly linked list


displayDlList(); // Display the created doubly linked list
return 0;
}

// Function to create a doubly linked list


void DlListcreation(int n) {
int i, num;
struct node *fnNode;

if (n >= 1) {
stnode = (struct node *)malloc(sizeof(struct node)); // Allocate memory for
the first node

if (stnode != NULL) {
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode->num = num;
stnode->preptr = NULL;
stnode->nextptr = NULL;
ennode = stnode; // Assign stnode as the last node

// Create nodes and link them to form the doubly linked list
for (i = 2; i <= n; i++) {
fnNode = (struct node *)malloc(sizeof(struct node));
if (fnNode != NULL) {
printf(" Input data for node %d : ", i);
scanf("%d", &num);
fnNode->num = num;
fnNode->preptr = ennode;
fnNode->nextptr = NULL;

ennode->nextptr = fnNode;
ennode = fnNode;
} else {
printf(" Memory can not be allocated.");
break;
}
}
} else {
printf(" Memory can not be allocated.");
}
}
}

// Function to display the doubly linked list


void displayDlList() {
struct node *tmp;
int n = 1;
if (stnode == NULL) {
printf(" No data found in the List yet.");
} else {
tmp = stnode;
printf("\n\n Data entered on the list are :\n");

// Traverse and display each node's data in the list


while (tmp != NULL) {
printf(" node %d : %d\n", n, tmp->num);
n++;
tmp = tmp->nextptr; // Move to the next node
}
}
}

37) Write a ‘C’ program to read n integers and create two lists such that all
positive numbers are in one list and negative numbers are in another list.
Display both the lists.

// C program to find the count of positive


// and negative integers in an array

#include <stdio.h>

// Function to find the count of


// positive integers in an array
int countPositiveNumbers(int* arr, int n)
{
int pos_count = 0;
int i;
for (i = 0; i < n; i++) {
if (arr[i] > 0)
pos_count++;
}
return pos_count;
}

// Function to find the count of


// negative integers in an array
int countNegativeNumbers(int* arr, int n)
{
int neg_count = 0;
int i;
for (i = 0; i < n; i++) {
if (arr[i] < 0)
neg_count++;
}
return neg_count;
}

// Function to print the array


void printArray(int* arr, int n)
{
int i;

printf("Array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

// Driver program
int main()
{
int arr[] = { 2, -1, 5, 6, 0, -3 };
int n;
n = sizeof(arr) / sizeof(arr[0]);

printArray(arr, n);

printf("Count of Positive elements = %d\n",


countPositiveNumbers(arr, n));
printf("Count of Negative elements = %d\n",
countNegativeNumbers(arr, n));

return 0;
}

You might also like