Matrix

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

1.

MATRIX

#include<stdio.h>
typedef struct{
int row;
int col;
int value;
}term;
term a[100],b[100];
void transpose(term a[],term b[])
{
int i,j,n;
n=a[0].value;
b[0].row=a[0].col;
b[0].col=a[0].row;
b[0].value=n;
if(n>0)
{
int currentb=1;
for(i=0;i<a[0].col;i++)
{
for (j=1;j<=n;j++)
{
if (a[j].col==i)
{
b[currentb].row=a[j].col;
b[currentb].col=a[j].row;
b[currentb].value=a[j].value;
currentb++;
}
}
}
}
}
void fastTranspose(term a[],term b[])
{
int row_terms[50],start_pos[50],i,j,num_terms;
num_terms = a[0].value;
b[0].row=a[0].col;
b[0].col=a[0].row;
b[0].value=num_terms;
if(num_terms>0){
for(i=0;i<a[0].col;i++)
row_terms[i]=0;
for(i=1;i<a[0].col;i++)
row_terms[a[i].col]++;
start_pos[0]=1;
for(i=1;i<a[0].col;i++)
start_pos[i]=start_pos[i-1]+row_terms[i-1];
for(i=1;i<=num_terms;i++)
{
j=start_pos[a[i].col]++;
b[j].row = a[i].col;
b[j].col = a[i].row;
b[j].value = a[i].value;
}
}
}
void readSparse(term a[])
{
for(int i=1;i<=a[0].value;i++)
{
printf("Enter the term %d (row, column, value): ",i);
scanf("%d%d%d",&a[i].row,&a[i].col,&a[i].value);
}
}
void displaySparse(term a[])
{
for(int i=0;i<=a[0].value;i++)
{
printf("%d %d %d",a[i].row,a[i].col,a[i].value);
printf("\n");
}
}
void main()
{

printf("Enter the number of rows of Sparse Matrix: ");


scanf("%d%d",&a[0].row,&a[0].col);
printf("Enter the number of non zero elements: ");
scanf("%d",&a[0].value);
readSparse(a);
transpose(a,b);
printf("\nOriginal Sparse Matrix:\n");
displaySparse(a);
printf("\nTranspose pf Sparse Matrix:\n");
displaySparse(b);
fastTranspose(a,b);
printf("\nTranspose using fast transpose\n");
displaySparse(b);
}

2. PATTERN MATCHING
#include<stdio.h>
#include<string.h>
int failure[100];
int nfind(char *string, char *pat){
int i,j,start=0;
int lasts=strlen(string)-1;
int lastp=strlen(pat)-1;
int endmatch=lastp;

for(i=0;endmatch<=lasts;endmatch++,start++){
if(string[endmatch]==pat[lastp])
for(j=0,i=start;j<lastp&&string[i]==pat[j];i++,j++);
if(j==lastp)
return start;
}
return -1;
}
int pmatch(char *string,char *pat){
int i=0,j=0;
int lens = strlen(string);
int lenp = strlen(pat);
while(i<lens && j< lenp){
if (string[i]==pat[j]){
i++;j++;}
else if(j==0)i++;
else j=failure[j-1]+1;
}
return ((j==lenp) ? (i-lenp): -1);
}
void fail(char *pat){
int n=strlen(pat);
failure[0] = -1;
for(int j=1;j<n;j++){
int i=failure[j-1];
while ((pat[j]!=pat[i+1])&& i>=0)
i=failure[i];
if (pat[j]==pat[i+1])
failure[j]=i+1;
else
failure[j]=-1;
}
}
void main(){
char string[50],pat[50];
int pos;
printf("Enter the string: ");
scanf("%s",string);
printf("Enter the pattern: ");
scanf("%s",pat);
pos=nfind(string,pat);
if(pos>=0)
printf("\nThe pattern \"%s\" is found in \"%s\" at position
%d",pat,string,pos);
else
printf("\nThe pattern \"%s\" is not found in \"%s\".",pat,string);
fail(pat);
pos=pmatch(string,pat);
if(pos>=0)
printf("\nPattern \"%s\" is found in the string \"%s\" at position
%d",pat,string,pos);
else
printf("\nPattern \"%s\" is not found in the string");
}
3. INFIX TO POSTFIX
#include<stdio.h>
typedef enum{lparen,rparen,plus,minus,times,divide,mod,eos,operand}precedence;
int top = -1;
int isp[]={0,19,12,12,13,13,13,0};
int icp[]={20,19,12,12,13,13,13,0};
char expr[50];
precedence stack[50];
precedence operatorValue(char *symbol, int *n){
*symbol = expr[(*n)++];
switch(*symbol){
case '(': return lparen;
case ')': return rparen;
case '+': return plus;
case '-': return minus;
case '*': return times;
case '/': return divide;
case '%': return mod;
case '\0': return eos;
default: return operand;
}
}

void printOperator(precedence token){


switch(token){
case plus: printf("+"); break;
case minus: printf("-"); break;
case times: printf("*"); break;
case divide: printf("/"); break;
case mod: printf("%%"); break;

}
}

void push(precedence token){


stack[++top]=token;
}

precedence pop(){
return stack[top--];
}
void Postfix()
{
char symbol;
precedence token;
int n=0;
top=0;
stack[0]=eos;
token = operatorValue(&symbol,&n);
while(token!=eos){
if (token == operand){
printf("%c",symbol);
}
else if (token==rparen){
while(stack[top]!=lparen)
printOperator(pop());
pop();
}
else{
while(isp[stack[top]]>=icp[token]){
printOperator(pop());
}
push(token);
}
token = operatorValue(&symbol,&n);

}
while((token=pop())!=eos)
printOperator(token);
printf("\n");

int main(){
printf("\nEnter the Infix Expression: ");
scanf("%s",expr);
printf("\nThe Postfix Expression: \n");
Postfix();
return 0;
}
4. POSTFIX EVALUATION
#include<stdio.h>
typedef enum{lparen,rparen,plus,minus,times,divide,mod,eos,operand}precedence;
int top=-1;
char expr[50];
int stack[50];
precedence operatorValue(char *symbol,int *n){
*symbol=expr[(*n)++];
switch(*symbol){
case '(':return lparen;
case ')':return rparen;
case '+':return plus;
case '-':return minus;
case '*':return times;
case '/':return divide;
case '%':return mod;
case '\0':return eos;
default:return operand;
}
}

void push(int num){


stack[++top]=num;}

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

int eval(void){
precedence token;
char symbol;
int op1,op2;
int n=0;
token=operatorValue(&symbol,&n);
while(token!=eos){
if(token==operand)
push(symbol-'0');
else{
op2=pop();
op1=pop();
switch(token){
case plus:push(op1+op2);
break;
case minus:push(op1-op2);
break;
case times:push(op1*op2);
break;
case divide:push(op1/op2);
break;
case mod:push(op1%op2);
break;
}
}
token=operatorValue(&symbol,&n);
}
return pop();
}

int main(){
printf("enter the postfix exp.:-");
scanf("%s",expr);
printf("the evaluated result:\n%d\n",eval());
return 0;
}

5. CIRCULAR QUEUES
#include<stdio.h>
#include<stdlib.h>
typedef struct{
int key;
}element;
int front=-1, rear=-1, capacity;
element *queue;
void copy(element* sourcestart, element* sourceend, element* deststart)
{
while (sourcestart<sourceend){
deststart->key = sourcestart->key;
sourcestart++;
deststart++;
}

}
void queueFull()
{
element* newQueue;
newQueue = (element*)malloc(2*capacity*sizeof(*queue));
if (newQueue == NULL) {
fprintf(stderr, "Memory allocation error during resize.\n");
exit(EXIT_FAILURE);
}
int start=(front+1)%capacity;
if(start < 2)
copy(queue+start, queue+start+capacity-1, newQueue);
else
{
copy(queue+start, queue+capacity , newQueue);
copy(queue, queue+rear+1, newQueue+capacity-start);
}
front=2*capacity-1;
rear=capacity-1;
capacity*=2;
free(queue);
queue=newQueue;
}
void enqueue(element item)
{
rear=(rear+1)%capacity;
if(front==rear || (front == -1 && rear == capacity-1))
queueFull();
(queue+rear)->key = item.key;
}
element dequeue()
{
element item;
if(front==rear)
{
item.key=-1;
return item;
}
front=(front+1)%capacity;
item.key = (queue+front)->key;
return item;
}
void printq()
{
int i;
if(front==rear)
{
printf("\nQueue is Empty\n");
return;
}
for(i=(front+1)%capacity; i!=rear; i=(i+1)%capacity)
printf("%d\t",(queue+i)->key);
printf("%d", (queue+i)->key);
printf("\n");
printf("\nFront: %d Rear: %d\n", front, rear);
}
void main()
{
int choice;
element item;
printf("Enter intial size of queue: ");
scanf("%d",&capacity);
queue = (element *)malloc(capacity*sizeof(element));
if (queue == NULL) {
fprintf(stderr, "Memory allocation error.\n");
exit(EXIT_FAILURE);
}
while(1)
{
printf("\n 1. Add\n 2. Delete\n 3. Display\n 4. Exit\n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("\nEnter item to insert: ");
scanf("%d",&item.key);
enqueue(item);
break;
}
case 2:
{
item=dequeue();
if(item.key==-1)
printf("\nQueue is Empty.\n");
else
printf("\nItem deleted: %d \n", item.key);
break;
}
case 3:
{
printq();
break;
}
case 4:
{
exit(0);
break;
}
default: printf("\nInvalid input!!\n");
}
}
}

6. STACKS
#include<stdio.h>
#include<stdlib.h>
typedef struct{
int key;
}element;
typedef struct stack{
element data;
struct stack *link;
}stack;
typedef struct stack *stackptr;
stackptr top;
void push(element item){
if(top==NULL){
top = (stackptr)malloc(sizeof(stackptr));
top->data = item;
top->link = NULL;
}
else{
stackptr temp;
temp = (stackptr)malloc(sizeof(stackptr));
temp->data = item;
temp->link = top;
top=temp;
}
}
element pop(){
stackptr temp,ref;
element item;
ref = top;
if (ref==NULL){
item.key = -1;
return item;
}
else{
ref = ref->link;
}
item = top->data;
free(top);
top = ref;
return item;
}
void display(){
stackptr ref = top;
if (ref == NULL){
printf("Stack is empty.");
return;
}
printf("The stack elements are: \n");
while(ref){
printf("%d\t",ref->data);
ref=ref->link;
}
}
int main() {
int choice;
element value;
printf("\nImplementation of Stack using Linked List\n");
while (1) {
printf("\n\n1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("\nEnter your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the value to insert: ");
scanf("%d", &value.key);
push(value);
break;
case 2:
value = pop();
if (value.key==-1){
printf("Stack is empty.");
}
else{
printf("Popped element is :%d\n", value.key);
}
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong Choice\n");
}
}
}

7. QUEUE USING LINKED LIST


#include<stdio.h>
#include<stdlib.h>
typedef struct{
int key;
}element;
typedef struct queue{
element data;
struct queue *link;
};
typedef struct queue *queueptr;
queueptr front, rear;
void enqueue(element item){
queueptr temp;
temp = (queueptr)malloc(sizeof(queueptr));
temp->data = item;
if(front){
rear->link=temp;
}
else{
front=temp;
}
rear=temp;
}
element dequeue(){
queueptr temp,ref;
element item;
temp = front;
if (!front){
item.key = -1;
return item;
}
else{
item=temp->data;
front=front->link;
}
free(temp);
return item;
}
void display(){
queueptr ref = front;
if (ref == NULL){
printf("Queue is empty.");
return;
}
printf("The queue elements are: \n");
while(ref){
printf("%d\t",ref->data.key);
ref=ref->link;
}
}
int main() {
int choice;
element value;
printf("\nImplementation of Stack using Linked List\n");
while (1) {
printf("\n\n1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\n");
printf("\nEnter your choice : ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the value to insert: ");
scanf("%d", &value.key);
enqueue(value);
break;
case 2:
value = dequeue();
if (value.key==-1){
printf("Queue is empty.");
}
else{
printf("Dequeued element is :%d\n", value.key);
}
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong Choice\n");
}
}
}

8. Write and implement a C program to perform the following using linked


lists.

a. Create Linked lists to store two polynomials (20 marks)


b. Add two polynomials (15 marks)

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

#define COMPARE(x, y) ((x > y) ? 1 : (x == y) ? 0 : -1)

struct polyNode {
int coeff;
int expon;
struct polyNode *link;
};

typedef struct polyNode *polyptr;


void attach(int coefficient, int exponent, polyptr *ptr) {
polyptr temp, p;
temp = (polyptr)malloc(sizeof(struct polyNode));
temp->coeff = coefficient;
temp->expon = exponent;
temp->link = NULL; // Mark the new node as the end

/* If the list is empty, create a new list */


if (*ptr == NULL) {
*ptr = temp;
return;
}

/* Go to the last node */


p = *ptr;
while (p->link != NULL) {
p = p->link;
}

/* Attach the new node at the end */


p->link = temp;
}

polyptr padd(polyptr a, polyptr b) {


polyptr c = NULL, rear = NULL;
int sum;

while (a && b) {
switch (COMPARE(a->expon, b->expon)) {
case 1:
attach(a->coeff, a->expon, &rear);
a = a->link;
break;
case -1:
attach(b->coeff, b->expon, &rear);
b = b->link;
break;
case 0:
sum = a->coeff + b->coeff;
if (sum) {
attach(sum, a->expon, &rear);
}
a = a->link;
b = b->link;
}
}

for (; a; a = a->link) attach(a->coeff, a->expon, &rear);


for (; b; b = b->link) attach(b->coeff, b->expon, &rear);

return rear;
}

void readPoly2(polyptr *a) {


*a = NULL;
int expon, coeff, n, i = 0;
printf("Enter number of terms: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("Enter coeff and exponent of term %d: ", i + 1);
scanf("%d%d", &coeff, &expon);
attach(coeff, expon, a);
}
}

void printPoly(polyptr a) {
for (; a; a = a->link) {
printf("%dx^%d", a->coeff, a->expon);
if (a->link) {
printf(" + ");
}
}
printf("\n");
}

int main() {
polyptr a, b, c;
readPoly2(&a);
printf("Polynomial 1: ");
printPoly(a);
readPoly2(&b);
printf("Polynomial 2: ");
printPoly(b);
c = padd(a, b);
printf("\nSum of two polynomials: ");
printPoly(c);
return 0;
}
9. DOUBLY LL

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

// Define the structure of a node


typedef struct node *nodePointer;
typedef struct node {
nodePointer llink;
int data;
nodePointer rlink;
} Node;

// Function to insert a node after a given node


void dinsert(nodePointer node, nodePointer newnode) {
newnode->llink = node;
newnode->rlink = node->rlink;
node->rlink->llink = newnode;
node->rlink = newnode;
}

// Function to delete a given node


void ddelete(nodePointer node, nodePointer deleted) {
if (node == deleted) {
printf("Deletion of head node not permitted.\n");
} else {
deleted->llink->rlink = deleted->rlink;
deleted->rlink->llink = deleted->llink;
free(deleted);
}
}

// Function to display the list


void displayList(nodePointer head) {
nodePointer temp = head->rlink;
printf("Doubly Linked List: ");
while (temp != head) {
printf("%d ", temp->data);
temp = temp->rlink;
}
printf("\n");
}

int main() {
// Create a head node
nodePointer head = (nodePointer)malloc(sizeof(Node));
printf("Create head node.\n");

head->llink = head;
head->rlink = head;

// Insert some nodes


nodePointer node1 = (nodePointer)malloc(sizeof(Node));
printf("Create Node 1.\n");
node1->data = 1;

dinsert(head, node1);
printf("Insert Node 1\n");

nodePointer node2 = (nodePointer)malloc(sizeof(Node));


printf("Create Node 2\n");
node2->data = 2;
dinsert(node1, node2);
printf("Insert Node 2\n");

nodePointer node3 = (nodePointer)malloc(sizeof(Node));


printf("Create Node 3\n");
node3->data = 3;
dinsert(node2, node3);
printf("Insert Node 3\n");

// Display the list


displayList(head);

// Delete a node
ddelete(head, node2);
printf("After deletion of node 2:\n");

// Display the list after deletion


displayList(head);

// Free allocated memory


free(node1);
free(node3);
free(head);

return 0;
}

10. BINARY SEARCH TREES

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

// Define the structure of a node


typedef struct node *treeptr;
typedef struct node {
int data;
treeptr left, right;
} Node;

// Function to create a new node


treeptr newNode(int item) {
treeptr temp = (treeptr)malloc(sizeof(Node));
if (temp == NULL) {
fprintf(stderr, "Memory allocation failed!\n");
exit(1);
}
temp->data = item;
temp->left = NULL;
temp->right = NULL;
return temp;
}

// Function to insert a node into the binary search tree


treeptr insert(treeptr node, int item) {
if (node == NULL)
return newNode(item);
if (item < node->data)
node->left = insert(node->left, item);
else if (item > node->data)
node->right = insert(node->right, item);
return node;
}

// Function for inorder traversal


void inorder(treeptr ptr) {
if (ptr) {
inorder(ptr->left);
printf("%d ", ptr->data);
inorder(ptr->right);
}
}

// Function for preorder traversal


void preorder(treeptr ptr) {
if (ptr) {
printf("%d ", ptr->data);
preorder(ptr->left);
preorder(ptr->right);
}
}

// Function for postorder traversal


void postorder(treeptr ptr) {
if (ptr) {
postorder(ptr->left);
postorder(ptr->right);
printf("%d ", ptr->data);
}
}

// Function to search for a node in the binary search tree


treeptr search(treeptr root, int key) {
if (root == NULL || root->data == key)
return root;
if (root->data < key)
return search(root->right, key);
return search(root->left, key);
}

int main() {
treeptr root = NULL;

// Insert nodes into the binary search tree


root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);

// Perform inorder traversal


printf("Inorder traversal: ");
inorder(root);
printf("\n");

// Perform preorder traversal


printf("Preorder traversal: ");
preorder(root);
printf("\n");

// Perform postorder traversal


printf("Postorder traversal: ");
postorder(root);
printf("\n");

// Search for a node


int key = 40;
treeptr result = search(root, key);
if (result)
printf("%d found in the tree.\n", key);
else
printf("%d not found in the tree.\n", key);

return 0;
}

10. MAX HEAP OPERATIONS

#include<stdio.h>
#include <stdlib.h>
#define MAX_SIZE 10
typedef struct{
int key;
}element;
element heap[MAX_SIZE];
void insert(element item, int *n){
int i;
if((*n)==MAX_SIZE-1){
printf("Heap Full\n");
return;
}
i=++(*n);
while(i!=1 && item.key>heap[i/2].key){
heap[i]=heap[i/2];
i/=2;
}
heap[i]=item;
}
element deleteHeap(int* n)
{
int parent, child;
element temp, item;
if(*n==0){
printf("Heap Empty\n");
item.key=-1;
return item;
}
item = heap[1];
temp = heap[(*n)--];
parent = 1;
child = 2;
while(child<=*n)
{
if(child<*n && heap[child].key < heap[child+1].key)
child++;
if(temp.key >= heap[child].key)
break;
heap[parent]=heap[child];
parent=child;
child=child*2;
}
heap[parent]=temp;
return item;
}
void display(int n)
{
int i;
for(i=1;i<=n;i++)
{
printf("%d\n",heap[i].key);
}
}
int main()
{
int choice,n=0;
element item;
while(1)
{
printf("Enter\n 1. Insert\n 2. Display\n 3. Delete\n 4. Exit");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter element to insert");
scanf("%d", &item.key);
insert(item, &n);
break;
case 2:
display(n);
break;
case 3:
item = deleteHeap(&n);
if(item.key!=-1)
printf("Element Deleted: %d\n",item.key);
break;
case 4:
exit(0); }
}
}

12. GRAPH OPERATIONS

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

#define MAX_VERTICES 50
#define FALSE 0
#define TRUE 1

typedef struct node *node_pointer;


typedef struct node {
int vertex;
struct node *link;
} node;

typedef struct queue *queue_pointer;


typedef struct queue {
int vertex;
queue_pointer link;
} queue;

node_pointer graph[MAX_VERTICES];
short int visited[MAX_VERTICES];
int n = 0; /* vertices currently in use */
void insert(int vi, int vj);
void readgraph();
void dfs(int v);
void bfs(int v);
void addq(queue_pointer *front, queue_pointer *rear, int v);
int deleteq(queue_pointer *front);

int main() {
readgraph();

printf("DFS Traversal: ");


dfs(0); // Start DFS from vertex 0

// Reset visited array


for (int i = 0; i < MAX_VERTICES; i++) {
visited[i] = FALSE;
}

printf("\nBFS Traversal: ");


bfs(0); // Start BFS from vertex 0

return 0;
}

void readgraph() {
int i, vi, vj, no_of_edges;
printf("Enter no. of vertices: ");
scanf("%d", &n);

// Initialize graph[] with NULL


for (i = 0; i < n; i++)
graph[i] = NULL;
// Read edges and insert them in graph[]
printf("Enter no of edges: ");
scanf("%d", &no_of_edges);
for (i = 0; i < no_of_edges; i++) {
printf("Enter an edge (u, v): ");
scanf("%d%d", &vi, &vj);
insert(vi, vj);
insert(vj, vi);
}
}

void insert(int vi, int vj) {


node *p, *q;
// Acquire memory for the new node
q = (node *)malloc(sizeof(node));
q->vertex = vj;
q->link = NULL;
// Insert the node in the linked list for the vertex no. vi
if (graph[vi] == NULL)
graph[vi] = q;
else {
// Go to the end of linked list
p = graph[vi];
while (p->link != NULL)
p = p->link;
p->link = q;
}
}

void dfs(int v) {
node_pointer w;
visited[v] = TRUE;
printf("%5d", v);
for (w = graph[v]; w; w = w->link)
if (!visited[w->vertex])
dfs(w->vertex);
}

void bfs(int v) {
node_pointer w;
queue_pointer front, rear;
front = rear = NULL;
printf("%5d", v);
visited[v] = TRUE;
addq(&front, &rear, v);
while (front) {
v = deleteq(&front);
for (w = graph[v]; w; w = w->link)
if (!visited[w->vertex]) {
printf("%5d", w->vertex);
addq(&front, &rear, w->vertex);
visited[w->vertex] = TRUE;
}
}
}

void addq(queue_pointer *front, queue_pointer *rear, int v) {


queue_pointer temp;
temp = (queue_pointer)malloc(sizeof(queue));
temp->vertex = v;
temp->link = NULL;
if (*front) {
(*rear)->link = temp;
*rear = temp;
} else
*front = *rear = temp;
}
int deleteq(queue_pointer *front) {
queue_pointer temp;
int v;
temp = *front;
v = temp->vertex;
*front = (*front)->link;
free(temp);
return v;
}

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