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

DSA Lab Programs

The document outlines multiple C programs for various data structure operations including array manipulation, string pattern matching, stack operations, infix to postfix conversion, suffix expression evaluation, and circular queue management. Each program is designed with a menu-driven interface and includes functions for specific tasks such as creating, displaying, inserting, and deleting elements. Additionally, there are implementations for linked lists and stack applications like the Tower of Hanoi problem.

Uploaded by

jbhoomi75
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)
9 views

DSA Lab Programs

The document outlines multiple C programs for various data structure operations including array manipulation, string pattern matching, stack operations, infix to postfix conversion, suffix expression evaluation, and circular queue management. Each program is designed with a menu-driven interface and includes functions for specific tasks such as creating, displaying, inserting, and deleting elements. Additionally, there are implementations for linked lists and stack applications like the Tower of Hanoi problem.

Uploaded by

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

PROGRAM 1

Design, Develop and Implement a menu driven Program in C for the following Array operations
a. Creating an Array of N Integer Elements
b. Display of Array Elements with Suitable Headings
c. Inserting an Element (ELEM) at a given valid Position (POS)
d. Deleting an Element at a given valid Position (POS)
e. Exit.
Support the program with functions for each of the above operations.

#include<stdio.h>
#include<stdlib.h>
int a[20];
int n, val, i, pos, choice;
/*Function Prototype*/
void create();
void display();
void insert();
void delet();
int main()
{
while(1)
{
printf("\n\n--------MENU ---------- \n");
printf("1.CREATE\n");
printf("2.DISPLAY\n");
printf("3.INSERT\n");
printf("4.DELETE\n");
printf("5.EXIT\n");
printf(" ---------------------- ");
printf("\nENTER YOUR CHOICE:\t");
scanf("%d",&choice); //Reading user choice
switch(choice)
{
case 1: create(); //to create an array
break;
case 2: if(n)
display(); //to display the elements
else
{
printf("Array is empty\n");
}
break;
case 3: :insert(); // to insert elements
break;

case 4:if(n)
delet(); //to delete an item at specific position
else
{
printf("Array is empty\n");
}
break;
case 5: exit(0); //exit the program
break;
default:printf("\nInvalid choice:\n");
break;
}
}
return 0;
}
//creating an array
void create()
{
printf("\nEnter the size of the array elements:\t");
scanf("%d",&n);
printf("\nEnter the elements for the array:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
}
//displaying an array elements
void display()
{
int i;
printf("\nThe array elements are:\n");
for(i=1;i<=n;i++)
{
printf("%d\t",a[i]);
}
}
//inserting an element into an array
void insert()
{
printf("\nEnter the position for the new element:\t");
scanf("%d",&pos);
if(pos>(n+1))
printf("\n Invalid Position\n");
else
{
printf("\nEnter the element to be inserted :\t");
scanf("%d",&val);
for(i=n;i>=pos;i--)
{
a[i+1]=a[i];
}
a[pos]=val;
n=n+1;
}
}
//deleting an array element
void delet()
{
printf("\nEnter the position of the element to be deleted:\t");
scanf("%d",&pos);
if(pos>n)
printf("Invalid Position\n");
else
{
val=a[pos];
for(i=pos;i<n;i++)
{
a[i]=a[i+1];
}
n=n-1;
printf("\nThe deleted element is =%d",val);
}
}
OUTPUT:
PROGRAM 2
Design, develop and implement a Program in C for the following operations on Strings
a. Read a main String (STR), a Pattern String (PAT) and a Replace String (REP)
b. Perform Pattern Matching Operation: Find and Replace all occurrences of PAT in STR
with REP if PAT exists in STR. Report suitable messages in case PAT does not exist in STR
Support the program with functions for each of the above operations. Don't use Built-in functions.
#include<stdio.h>
int flag=0;
void readinput(char str[],char pat[],char rep[])
{
printf("Enter the Main String\n");
gets(str);
printf("Enter the Pattern String\n");
gets(pat);
printf("Enter the Replacement String\n");
gets(rep);
}
void patternmatch(char str[],char pat[],char rep[], char ans[])
{
int i,j,c,m,k;
i=j=c=m=k=0;

while(str[c] != '\0')
{
if(str[m] == pat[i])
{
i++;m++;
if(pat[i]=='\0')
{
flag=1;
for(k=0;rep[k] != '\0';k++,j++)
ans[j] = rep[k];
i=0;
c=m;
}
}
else
{
ans[j] = str[c];
j++;c++;
m=c;
i=0;
}
}
ans[j]='\0';
}
void main()
{
char str[100],pat[100],rep[100],ans[100];
readinput(str,pat,rep);
patternmatch(str,pat,rep,ans);
if(flag == 0)
{
printf("Pattern Not Found\n");
printf("Resultant String is: %s\n", ans);
}
else
printf("Resultant String is: %s\n", ans);
}
OUTPUT:
PROGRAM 3
Design, Develop and Implement a menu driven Program in C for the following operations on
STACK of Integers (Array Implementation of Stack with maximum size MAX)
a. Push an Element on to Stack
b. Pop an Element from Stack
c. Demonstrate how Stack can be used to check Palindrome
d. Demonstrate Overflow and Underflow situations on Stack
e. Display the status of Stack
f. Exit
Support the program with appropriate functions for each of the above operations.
#include<stdlib.h>
#include<stdio.h>
#define max_size 5
int stack[max_size],top=-1;
/*Function Prototype*/
void push();
void pop();
void display();
void pali();
int main()
{
int choice;
while(1)
{
printf("\n\n--------STACK OPERATIONS ---------- \n");
printf("1.Push\n");
printf("2.Pop\n");
printf("3.Palindrome\n");
printf("4.Display\n");
printf("5.Exit\n");
printf(" ---------------------- ");
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1: push(); //to insert an item into stack
break;
case 2: pop(); //to delete an item from stack
break;
case 3: pali(); //to check palindrome or not
break;
case 4: display(); //to display items in stack
break;
case 5: exit(0);//exit the program
break;
default:printf("\n Invalid choice:\n");
break;
}
}
return 0;
}
void push() //Inserting element into the stack
{
int item,n;
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 pali() //checking whether palindrome or not
{
int num[10],rev[10],i=0,k,flag=1;
k=top;
while(k!=-1)
{
num[i++]=stack[k--];
}
for(i=0;i<=top;i++)
{
if(num[i]==stack[i])
continue;
else
flag=0;
}
if(top!=-1)
{
if(flag)
printf("It is palindrome number\n");
else
printf("It is not a palindrome number\n");
}
else
printf("Stack is Empty:");
}
void display() //Displaying the elements of stack
{
int i;
if(top==-1)
{
printf("\nStack is Empty:");

}
else
{
printf("\nThe stack elements are:\n" );
for(i=top;i>=0;i--)
{
printf("%d\t",stack[i]);
}
}
}

OUTPUT:
PROGRAM 4
Design, develop and implement a Program in C for converting an Infix Expression to Postfix
Expression. Program should support for both parenthesized and free parenthesized expressions
with the operators: +, -, *, /, %(Remainder), ^(Power) and alphanumeric operands.
#include <ctype.h>
#include <stdio.h>
#define SIZE 50 /* Size of Stack */
char s[SIZE]; /* Global declarations */
int top = -1;
push(char elem) /* Function for PUSH operation */
{
s[++top] = elem;
}
char pop() /* Function for POP operation */
{
return (s[top--]);
}
int pr(char elem) /* Function for precedence */
{
switch (elem)
{
case '#': return 0;
case '(': return 1;
case '+':
case '-': return 2;
case '*':
case '/':
case '%': return 3;
case '^': return 4;
}
}
void main() /* Main Program */
{
char infx[50], pofx[50], ch, elem;
int i = 0, k = 0;
printf("\n\n enter the Infix Expression : ");
gets(infx);
push('#');
while ((ch = infx[i++]) != '\0')
{
if (ch == '(')
push(ch);
else if (isalnum(ch))
pofx[k++] = ch;
else if (ch == ')')
{
while (s[top] != '(')
pofx[k++] = pop();
elem = pop(); /* Remove ( */
}
else /* Operator */
{
while (pr(s[top]) >= pr(ch))
pofx[k++] = pop();
push(ch);
}
}
while (s[top] != '#') /* Pop from stack till empty */
pofx[k++] = pop();
pofx[k] = '\0'; /* Make pofx as valid string */
printf("\n\n Given Infix Expn is: %s\n The Postfix Expn is:%s\n", infx, pofx);
}

OUTPUT:

OR
#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;
}
Output-1:
Enter the expression : a+b*c
abc*+

Output-2:
Enter the expression : (a+b)*c+(d-a)

ab+c*da-+

Output-3:
Enter the expression : ((4+8)(6-5))/((3-2)(2+2))
48+65-32-22+/

PROGRAM 5
Design, develop and implement a Program in C for the following Stack Applications
a. Evaluation of Suffix expression with single digit operands and operators: +, -, *, /,%, ^
b. Solving Tower of Hanoi problem with n disks
Source Code for program 5a:
#include<stdio.h>
#include<math.h>
#include<string.h>
int s[30],op1,op2;
int top=-1,i;
char p[30],sym;
int op(int op1,char sym,int op2)
{
switch(sym)
{
case '+':return op1+op2;
case '-':return op1-op2;
case '*':return op1*op2;
case '/':return op1/op2;
case '%':return op1%op2;
case '^':
case '$':return pow(op1,op2);
}
return 0;
}
int main()
{
printf("\nEnter the valid postfix exp:");
scanf("%s",p);
for(i=0;i<strlen(p);i++)
{
sym=p[i];
if(sym>='0' && sym<='9')
s[++top]=sym-'0';
else
{
op2=s[top--];
op1=s[top--];
s[++top]=op(op1,sym,op2);
}
}
printf("\nThe result is %d\n",s[top]);
}
OUTPUT:
Source Code for program 5b:

#include<stdio.h>
int count=0,n;
int tower(int n,char s,char t,char d)
{
if(n==1)
{
printf("\n Move disc 1 from %c to %c",s,d);
count++;
return 1;
}
tower(n-1,s,d,t);
printf("\n Move disc %d from %c to %c",n,s,d);
count++;
tower(n-1,t,s,d);
}
int main( )
{
printf("\n Enter the no. of discs:");
scanf("%d",&n);
tower(n,'A','B','C');
printf("\n The no. of disc moves is:%d",count);
}
OUTPUT:
PROGRAM 6
Design, develop and implement a menu driven Program in C for the following operations on
Circular QUEUE of Characters (Array Implementation of Queue with maximum size MAX)
a. Insert an Element on to Circular QUEUE
b. Delete an Element from Circular QUEUE
c. Demonstrate Overflow and Underflow situations on Circular QUEUE
d. Display the status of Circular QUEUE
e. Exit
Support the program with appropriate functions for each of the above operations.
#include<stdio.h>
#include<stdlib.h>
#define SIZE 5
char q[SIZE];
int i,r=-1;
int option,f=0;
int j,count=0;
void insert()
{
if(count==SIZE)
printf("\n Q is Full\n");
else
{
r=(r+1)%SIZE;
printf("\nEnter the item:");
scanf(" %c",&q[r]);
count++;
}
}
void delet()
{
if(count==0)
printf("\nQ is empty\n");
else
{
printf("\nDeleted item is: %c",q[f]);
count--;
f=(f+1)%SIZE;
}
}
void display()
{
if(count==0)
printf("\nQ is Empty\n");
else
{
i=f;
for(j=1;j<=count;j++)
{
printf(" %c",q[i]);
i=(i+1)%SIZE;
}
}
}
int main()
{
for(;;)
{
printf("\n1.Insert 2.Delete\n 3.Display 4.Exit");
printf("\nEnter your option:");
scanf("%d",&option);
switch(option)
{
case 1: insert();//Inserting items to Queue
break;
case 2: delet(); //Deleting items from Queue
break;
case 3:display(); //Displaying items from Queue
break;
default:exit(0);
}
}
}
OUTPUT:
PROGRAM 7
Develop a menu driven Program in C for the following operations on Singly Linked List (SLL) of Student Data
with the fields: USN, Name, Programme, Sem, PhNo
a. Create a SLL of N Students Data by using front insertion.
b. Display the status of SLL and count the number of nodes in it
c. Perform Insertion / Deletion at End of SLL
d. Perform Insertion / Deletion at Front of SLL(Demonstration of stack)
e. Exit
PROGRAM 8
Implementation of Basic Binary Tree in C

#include <stdio.h>
#include <stdlib.h>
// Structure for a node
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

/ Traversal - Inorder (Left, Root, Right)


void inorderTraversal(struct Node* root) {
if (root == NULL) return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
// Traversal - Preorder (Root, Left, Right)
void preorderTraversal(struct Node* root) {
if (root == NULL) return;
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}

// Traversal - Postorder (Left, Right, Root)


void postorderTraversal(struct Node* root) {
if (root == NULL) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}

int main()
{
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Inorder Traversal: ");
inorderTraversal(root);
printf("\nPreorder Traversal: ");
preorderTraversal(root);
printf("\nPostorder Traversal: ");
postorderTraversal(root);
return 0;
}
PROGRAM 9
Implementation of binary search tree in C

#include <stdio.h>
#include <stdlib.h>
// Define a node structure for the Binary Search Tree
struct Node {
int data;
struct Node* left;
struct Node* right;
};
// Function to create a new node
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
// Function to insert a node into the BST
struct Node* insert(struct Node* root, int data) {
// If the tree is empty, return a new node
if (root == NULL)
return createNode(data);
// Otherwise, recur down the tree
if (data < root->data)
root->left = insert(root->left, data);
else if (data > root->data)
root->right = insert(root->right, data);
// return the (unchanged) node pointer
return root;
}
// Function to search a value in the BST
struct Node* search(struct Node* root, int key) {
// Base case: root is null or key is present at the root
if (root == NULL || root->data == key)
return root;
// Key is greater than the root's data
if (key > root->data)
return search(root->right, key);
// Key is smaller than the root's data
return search(root->left, key);
}
// Function to do an in-order traversal of the tree
void inorder(struct Node* root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}

int main() {
struct Node* root = NULL;
// Insert nodes into the BST
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
// In-order traversal of the BST
printf("In-order traversal: ");
inorder(root);
printf("\n");
// Search for a node in the BST
int key = 40;
struct Node* result = search(root, key);
if (result != NULL)
printf("Node with value %d found in the BST.\n", key);
else
printf("Node with value %d not found in the BST.\n", key);
return 0;
}
PROGRAM 10
a. Implement Undirected Graph as Adjacency Matrix
b. Implement directed Graph as Adjacency Matrix.
a.
// Adjacency Matrix representation in C

#include <stdio.h>
#define V 4

// Initialize the matrix to zero


void init(int arr[][V]) {
int i, j;
for (i = 0; i < V; i++)
for (j = 0; j < V; j++)
arr[i][j] = 0;
}

// Add edges
void addEdge(int arr[][V], int i, int j) {
arr[i][j] = 1;
arr[j][i] = 1;
}

// Print the matrix


void printAdjMatrix(int arr[][V]) {
int i, j;

for (i = 0; i < V; i++) {


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

int main() {
int adjMatrix[V][V];

init(adjMatrix);
addEdge(adjMatrix, 0, 1);
addEdge(adjMatrix, 0, 2);
addEdge(adjMatrix, 1, 2);
addEdge(adjMatrix, 2, 0);
addEdge(adjMatrix, 2, 3);

printAdjMatrix(adjMatrix);

return 0;
}
b.
#include <stdio.h>
#include <stdlib.h>

#define MAX_VERTICES 100

// Structure to represent the graph


typedef struct {
int numVertices;
int adjMatrix[MAX_VERTICES][MAX_VERTICES];
} Graph;

// Function to initialize the graph


void initGraph(Graph* graph, int numVertices) {
graph->numVertices = numVertices;
for (int i = 0; i < numVertices; i++) {
for (int j = 0; j < numVertices; j++) {
graph->adjMatrix[i][j] = 0; // Initialize all edges to 0 (no edge)
}
}
}

// Function to add a directed edge to the graph


void addEdge(Graph* graph, int start, int end) {
if (start >= 0 && start < graph->numVertices && end >= 0 && end < graph->numVertices) {
graph->adjMatrix[start][end] = 1; // Set the edge from start to end to 1
} else {
printf("Invalid vertex indices.\n");
}
}

// Function to print the adjacency matrix


void printGraph(Graph* graph) {
printf("Adjacency Matrix:\n");
for (int i = 0; i < graph->numVertices; i++) {
for (int j = 0; j < graph->numVertices; j++) {
printf("%d ", graph->adjMatrix[i][j]);
}
printf("\n");
}
}

int main() {
int numVertices = 5;
Graph myGraph;

initGraph(&myGraph, numVertices);

addEdge(&myGraph, 0, 1);
addEdge(&myGraph, 0, 2);
addEdge(&myGraph, 1, 3);
addEdge(&myGraph, 2, 4);
addEdge(&myGraph, 3, 0);
addEdge(&myGraph, 4, 1);

printGraph(&myGraph);

return 0;
}

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