[go: up one dir, main page]

0% found this document useful (0 votes)
89 views30 pages

Data Stracture Lab

The document contains 6 code snippets that demonstrate various programming concepts: 1. A program that checks if a word is a palindrome by reversing the string and comparing it to the original. 2. A program that calculates the row sums, column sums, and grand total of a 2D array. 3. A program that performs matrix multiplication of two matrices input by the user. 4. A program that demonstrates push and pop operations on a stack using pointers. 5. A program that converts an infix expression to postfix notation. 6. A program that evaluates a postfix expression using a stack.

Uploaded by

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

Data Stracture Lab

The document contains 6 code snippets that demonstrate various programming concepts: 1. A program that checks if a word is a palindrome by reversing the string and comparing it to the original. 2. A program that calculates the row sums, column sums, and grand total of a 2D array. 3. A program that performs matrix multiplication of two matrices input by the user. 4. A program that demonstrates push and pop operations on a stack using pointers. 5. A program that converts an infix expression to postfix notation. 6. A program that evaluates a postfix expression using a stack.

Uploaded by

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

1. To write a program to check whether a word is palindrome or not.

#include <stdio.h>

#include <conio.h>

#include <string.h>

int main()

char string[25], reverse_string[25] = {'\0'};

int i, length = 0, flag = 0;

printf("Enter a string \n");

gets(string);

for (i = 0; string[i] != '\0'; i++)

length++;

printf("The length of the string '%s' = %d\n", string, length);

for (i = length - 1; i >= 0 ; i--)

reverse_string[length - i - 1] = string[i];

for (flag = 1, i = 0; i < length ; i++)

{
if (reverse_string[i] != string[i])

flag = 0;

if (flag == 1)

printf ("%s is a palindrome \n", string);

else

printf("%s is not a palindrome \n", string);

getch();

return 0;

}
2. To create a two dimensional array of numbers and calculate & display
the row & column sum and the grand total.
#include <stdio.h>

#include <conio.h>

int main()

int rows, cols, sumRow, sumCol,total_sumRow=0, total_sumCol=0;

int i,j;
//Initialize matrix a

int a[][3] = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

//Calculates number of rows and columns present in given matrix

rows = (sizeof(a)/sizeof(a[0]));

cols = (sizeof(a)/sizeof(a[0][0]))/rows;

//Calculates sum of each row of given matrix

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

sumRow = 0;

for(j = 0; j < cols; j++){

sumRow = sumRow + a[i][j];

total_sumRow=total_sumRow+sumRow;

printf("Sum of %d row: %d\n", (i+1), sumRow);

printf("Grand Total of %d row: %d\n", j, total_sumRow);


//Calculates sum of each column of given matrix

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

sumCol = 0;

for( j = 0; j < rows; j++){

sumCol = sumCol + a[j][i];

total_sumCol=total_sumCol+sumCol;

printf("Sum of %d column: %d\n", (i+1), sumCol);

printf("Grand Total of %d column: %d\n", i, total_sumCol);

getch();

return 0;

}
3. To write a program of matrix multiplication.
#include <stdio.h>

#include <conio.h>

int main()

int a[10][10],b[10][10],mul[10][10],r,c,i,j,k;
printf("enter the number of row=");

scanf("%d",&r);

printf("enter the number of column=");

scanf("%d",&c);

printf("enter the first matrix element=\n");

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

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

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

printf("enter the second matrix element=\n");

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

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

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

}
printf("multiply of the matrix=\n");

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

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

mul[i][j]=0;

for(k=0;k<c;k++)

mul[i][j]+=a[i][k]*b[k][j];

//for printing result

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

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

printf("%d\t",mul[i][j]);

printf("\n");

}
getch();

return 0;

}
4. To write a program to insert (Push) an element into the sack and delete
(Pop) an element from the stack using pointer
#include <stdio.h>

#include <conio.h>

int MAXSIZE = 8;

int stack[8];

int top = -1;

int isempty() {

if(top == -1)

return 1;

else

return 0;

int isfull() {
if(top == MAXSIZE)

return 1;

else

return 0;

int peek() {

return stack[top];

int pop() {

int data;

if(!isempty()) {

data = stack[top];

top = top - 1;

return data;

} else {

printf("Could not retrieve data, Stack is empty.\n");

}
int push(int data) {

if(!isfull()) {

top = top + 1;

stack[top] = data;

} else {

printf("Could not insert data, Stack is full.\n");

int main() {

// push items on to the stack

push(3);

push(5);

push(9);

push(1);

push(12);

push(15);

printf("Element at top of the stack: %d\n" ,peek());


printf("Elements: \n");

// print stack data

while(!isempty()) {

int data = pop();

printf("%d\n",data);

printf("Stack full: %s\n" , isfull()?"true":"false");

printf("Stack empty: %s\n" , isempty()?"true":"false");

getch();

return 0;

}
5. To write a program to convert an infix expression to a postfix expression
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<conio.h>
 
//char stack
char stack[25];
int top = -1;
 
void push(char item) {
   stack[++top] = item;
}
 
char pop() {
   return stack[top--];
}
 
//returns precedence of operators
int precedence(char symbol) {
 
   switch(symbol) {
      case '+':
      case '-':
         return 2;
         break;
      case '*':
      case '/':
         return 3;
         break;
      case '^':
         return 4;
         break;
      case '(':
      case ')':
      case '#':
         return 1;
         break;
   }
}
 
//check whether the symbol is operator?
int isOperator(char symbol) {
 
   switch(symbol) {
      case '+':
      case '-':
      case '*':
      case '/':
      case '^':
      case '(':
      case ')':
         return 1;
      break;
         default:
         return 0;
   }
}
 
//converts infix expression to postfix
void convert(char infix[],char postfix[]) {
   int i,symbol,j = 0;
   stack[++top] = '#';
      
   for(i = 0;i<strlen(infix);i++) {
      symbol = infix[i];
 
      if(isOperator(symbol) == 0) {
         postfix[j] = symbol;
         j++;
      } else {
         if(symbol == '(') {
            push(symbol);
         } else {
            if(symbol == ')') {
                          
               while(stack[top] != '(') {
                  postfix[j] = pop();
                  j++;
               }
 
               pop();   //pop out (.
            } else {
               if(precedence(symbol)>precedence(stack[top])) {
                  push(symbol);
               } else {
 
                  while(precedence(symbol)<=precedence(stack[top])) {
                     postfix[j] = pop();
                     j++;
                  }
                                        
                  push(symbol);
               }
            }
         }
      }
   }
 
   while(stack[top] != '#') {
      postfix[j] = pop();
      j++;
   }
      
   postfix[j]='\0';  //null terminate string.
}
 
//int stack
int stack_int[25];
int top_int = -1;
 
void push_int(int item) {
   stack_int[++top_int] = item;
}
 
char pop_int() {
   return stack_int[top_int--];
}
 
//evaluates postfix expression
int evaluate(char *postfix){
 
   char ch;
   int i = 0,operand1,operand2;
 
   while( (ch = postfix[i++]) != '\0') {
      
      if(isdigit(ch)) {
            push_int(ch-'0');  // Push the operand
      } else {
         //Operator,pop two  operands
         operand2 = pop_int();
         operand1 = pop_int();
 
         switch(ch) {
            case '+':
               push_int(operand1+operand2);
               break;
            case '-':
               push_int(operand1-operand2);
               break;
            case '*':
               push_int(operand1*operand2);
               break;
            case '/':
               push_int(operand1/operand2);
               break;
         }
      }
   }
 
   return stack_int[top_int];
}
 
void main() {
   char infix[25] = "1*(2+3)",postfix[25];
   convert(infix,postfix);
 
   printf("Infix expression is: %s\n" , infix);
   printf("Postfix expression is: %s\n" , postfix);
   printf("Evaluated expression is: %d\n" , evaluate(postfix));
   getch();
}

6. To evaluate a postfix expression.


#include<stdio.h>
#include<ctype.h>
#include<conio.h>
#define MAXSTACK 100
#define POSTFIXSIZE 100
 
 int stack[MAXSTACK];
 int top = -1 ;
 
 /* define push operation */
 void push(int item)
 {
 
     if(top >= MAXSTACK -1)
     {
         printf("stack over flow");
         return;
     }
     else
     {
         top = top + 1 ;
         stack[top]= item;
     }
 }
 
 /* define pop operation */
 int pop()
 {
     int item;
     if(top <0)
     {
        printf("stack under flow");
     }
     else
     {
         item = stack[top];
         top = top - 1;
         return item;
     }
 }
 
 /* define function that is used to input postfix expression and to
evaluate it */
 void EvalPostfix(char postfix[])
 {
 
    int i ;
    char ch;
    int val;
    int A, B ;
 
 
    /* evaluate postfix expression */
    for (i = 0 ; postfix[i] != ')'; i++)
    {
        ch = postfix[i];
        if (isdigit(ch))
        {
            /* we saw an operand,push the digit onto stack
            ch - '0' is used for getting digit rather than ASCII code of
digit */
            push(ch - '0');
        }
        else if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
        {
            /* we saw an operator
            * pop top element A and next-to-top elemnet B
            * from stack and compute B operator A
            */
            A = pop();
            B = pop();
 
            switch (ch) /* ch is an operator */
            {
                case '*':
                val = B * A;
                break;
 
                case '/':
                val = B / A;
                break;
 
                case '+':
                val = B + A;
                break;
 
                case '-':
                val = B - A;
                break;
            }
 
            /* push the value obtained above onto the stack */
            push(val);
        }
    }
    printf( " \n Result of expression evaluation : %d \n", pop()) ;
 }
 
 int main()
 {
 
    int i ;
 
    /* declare character array to store postfix expression */
    char postfix[POSTFIXSIZE];
    printf("ASSUMPTION: There are only four operators(*, /, +, -)
in an expression and operand is single digit only.\n");
    printf( " \nEnter postfix expression,\npress right parenthesis
')' for end expression : ");
 
    /* take input of postfix expression from user */
 
    for (i = 0 ; i <= POSTFIXSIZE - 1 ; i++)
    {
        scanf("%c", &postfix[i]);
 
        if ( postfix[i] == ')' ) /* is there any way to eliminate this if */
        { break; } /* and break statement */
    }
 
    /* call function to evaluate postfix expression */
 
    EvalPostfix(postfix);
   getch();
   
    return 0;
 }

7. write a program to insert an element in the queue and delete an element


from the queue using pointer.
#include<stdio.h>
#include<conio.h>
struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;
void insert(int);
void delete();
void display();
void main()
{
int choice, value;
clrscr();
printf("\n:: Queue Implementation using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d",&value);
insert(value);
break;
case 2: delete(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
getch();
}
}
}
void insert(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else{
rear -> next = newNode;
rear = newNode;
}
printf("\nInsertion is Success!!!\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d",temp->data);
temp = temp -> next;
}
printf("%d",temp->data);
}
}

8. To create a circular queue and add an element and delete an element


from a circular queue.
#include<stdio.h>

#include<conio.h>

# define MAX 5

int cqueue_arr[MAX];
int front = -1;

int rear = -1;

void insert(int item)

if((front == 0 && rear == MAX-1) || (front == rear+1))

printf("Queue Overflow \n");

return;

if(front == -1)

front = 0;

rear = 0;

else

if(rear == MAX-1)

rear = 0;

else

rear = rear+1;

}
cqueue_arr[rear] = item ;

void deletion()

if(front == -1)

printf("Queue Underflow\n");

return ;

printf("Element deleted from queue is : %d\n",cqueue_arr[front]);

if(front == rear)

front = -1;

rear=-1;

else

if(front == MAX-1)

front = 0;

else

front = front+1;
}

void display()

int front_pos = front,rear_pos = rear;

if(front == -1)

printf("Queue is empty\n");

return;

printf("Queue elements :\n");

if( front_pos <= rear_pos )

while(front_pos <= rear_pos)

printf("%d ",cqueue_arr[front_pos]);

front_pos++;

else

while(front_pos <= MAX-1)

{
printf("%d ",cqueue_arr[front_pos]);

front_pos++;

front_pos = 0;

while(front_pos <= rear_pos)

printf("%d ",cqueue_arr[front_pos]);

front_pos++;

printf("\n");

int main()

int choice,item;

do

printf("1.Insert\n");

printf("2.Delete\n");

printf("3.Display\n");

printf("4.Quit\n");
printf("Enter your choice : ");

scanf("%d",&choice);

switch(choice)

case 1 :

printf("Input the element for insertion in queue : ");

scanf("%d", &item);

insert(item);

break;

case 2 :

deletion();

break;

case 3:

display();

break;

case 4:

break;

default:

printf("Wrong choice\n");

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

return 0;

}
9.Write a program to reverse a linked list.
// Iterative C program to reverse a linked list
#include <stdio.h>
#include <stdlib.h>
 
/* Link list node */
struct Node {
            int data;
            struct Node* next;
};
 
/* Function to reverse the linked list */
static void reverse(struct Node** head_ref)
{
            struct Node* prev = NULL;
            struct Node* current = *head_ref;
            struct Node* next = NULL;
            while (current != NULL) {
                        // Store next
                        next = current->next;
 
                        // Reverse current node's pointer
                        current->next = prev;
 
                        // Move pointers one position ahead.
                        prev = current;
                        current = next;
            }
            *head_ref = prev;
}
 
/* Function to push a node */
void push(struct Node** head_ref, int new_data)
{
            struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
            new_node->data = new_data;
            new_node->next = (*head_ref);
            (*head_ref) = new_node;
}
 
/* Function to print linked list */
void printList(struct Node* head)
{
            struct Node* temp = head;
            while (temp != NULL) {
                        printf("%d ", temp->data);
                        temp = temp->next;
            }
}
 
/* Driver program to test above function*/
int main()
{
            /* Start with the empty list */
            struct Node* head = NULL;
            push(&head, 20);
            push(&head, 4);
            push(&head, 15);
            push(&head, 85);
            printf("Given linked list\n");
            printList(head);
            reverse(&head);
            printf("\nReversed Linked list \n");
            printList(head);
            getchar();
}

10. To create a circular linked list and insert & delete an element from the
list.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
 
 
/* Basic node structure. */
struct node {
    int data;
    struct node * next;
};
 
 
/* Functions declarations */
void createList(struct node ** head, int n);
void displayList(struct node ** head);
void deleteAll(struct node ** head, int key);
 
 
int main()
{
    int n, key, data, choice;
 
    struct node * head = NULL;
 
    /* Run forever until user chooses 0 */
    while(choice != 0)
    {
        printf("--------------------------------------------\n");
        printf("        CIRCULAR LINKED LIST PROGRAM        \n");
        printf("--------------------------------------------\n");
        printf("1. Create List\n");
        printf("2. Display list\n");
        printf("3. Delete all by key\n");
        printf("0. Exit\n");
        printf("--------------------------------------------\n");
        printf("Enter your choice : ");
 
        scanf("%d", &choice);
 
        switch(choice)
        {
            case 1:
                printf("Enter number of nodes to create: ");
                scanf("%d", &n);
                createList(&head, n);
                break;
 
            case 2:
                displayList(&head);
                break;
 
            case 3:
                printf("Enter key to delete from list: ");
                scanf("%d", &key);
                deleteAll(&head, key);
                break;
 
            case 0:
                exit(0);
                break;
 
            default:
                printf("Error! Invalid choice. Please choose between 0-3");
        }
 
        printf("\n\n\n\n");
    }
    getch();
    return 0;
}
 
 
/**
 * Delete all occurrence of an element by key from a
 * given circular linked list.
 */
void deleteAll(struct node ** head, int key)
{
    int i, count;
    struct node *prev, *cur;
 
    if (*head == NULL)
    {
        printf("List is empty.\n");
        return;
    }
 
    count = 0;
    cur   = *head;
    prev  = cur;
 
 
    // Find node before head node
    while (prev->next != *head)
    {
        prev = prev->next;
        count++;
    }
 
    // Iterate till first node
    i = 0;
    while (i <= count)
    {
        if (cur->data == key)
        {
            // Link prev node with next node of current
            if (cur->next != cur)
                prev->next = cur->next;
            else
                prev->next = NULL;
 
            // Adjust head node if needed
            if (cur == *head)
                *head = prev->next;
 
            // Delete current node
            free(cur);
 
            // Move current node ahead
            if (prev != NULL)
                cur = prev->next;
            else
                cur = NULL;
        }
        else
        {
            prev = cur;
            cur  = cur->next;
        }
 
 
        i++;
 
    }
}
 
 
/**
 * Create a circular linked list of n nodes.
 */
void createList(struct node ** head, int n)
{
    int i, data;
    struct node *prevNode, *newNode;
 
    prevNode = NULL;
 
    /* Creates and link n nodes */
    for(i=1; i<=n; i++)
    {
        newNode = malloc(sizeof(struct node));
 
        printf("Enter data of %d node: ", i);
        scanf("%d", &data);
 
        newNode->data = data;
        newNode->next = NULL;
 
        // Link the previous node with newly created node
        if (prevNode != NULL)
            prevNode->next = newNode;
 
        // Adjust head node
        if (*head == NULL)
            *head = newNode;
 
        // Move previous node ahead
        prevNode = newNode;
    }
 
    // Link last node with first node
    prevNode->next = *head;
 
    printf("\nCIRCULAR LINKED LIST CREATED SUCCESSFULLY\n");
}
 
 
/**
 * Display content of the linked list.
 */
void displayList(struct node ** head)
{
    struct node *current;
    int n = 1;
 
    if(*head == NULL)
    {
        printf("List is empty.\n");
        return;
    }
 
    current = *head;
    printf("DATA IN THE LIST:\n");
 
    do {
        printf("Data %d = %d\n", n, current->data);
 
        current = current->next;
        n++;
    }while(current != *head);
}

You might also like