Data Structure Program Practical Solution






 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

Ans:


#include<stdio.h>

#include<stdlib.h>

typedef struct node 

{

struct node *l,*r;

int data;

}NODE;

NODE *insert(NODE *h,int v)

{

NODE *temp;

temp=(NODE *)malloc(sizeof(NODE));

temp->data=v;

temp->l=NULL;

temp->r=NULL;

if(h==NULL)

{

h=temp;

}

else if(v<h->data) 

{

h->l=insert(h->l,v);

}

else if(v>h->data)

{

h->r=insert(h->r,v);

}

return h;

}

int main()

 {

int n,i,val;

NODE *head;

head=NULL;

printf("Enter How many nodes\t");

scanf("%d",&n);

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

{

printf("Enter value :");

scanf("%d",&val);

head=insert(head,val);

}

printf("\nDisplay :\n",insert);

}


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

Ans:

#include <stdio.h>

#include <stdlib.h>

#define MAXSIZE 10

 

void main()

{

    int array[MAXSIZE];

    int i, num, power;

    float x, polySum;

 

    printf("Enter the order of the polynomial \n");

    scanf("%d", &num);

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

    scanf("%f", &x);

    /*  Read the coefficients into an array */

    printf("Enter %d coefficients \n", num + 1);

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

    {

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

    }

    polySum = array[0];

    for (i = 1; i <= num; i++)

    {

        polySum = polySum * x + array[i];

    }

    power = num;

 

    printf("Given polynomial is: \n");

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

    {

        if (power < 0)

        {

            break;

        }

        

        if (array[i] > 0)

            printf(" + ");

        else if (array[i] < 0)

            printf(" - ");

        else

            printf(" ");

        printf("%dx^%d  ", abs(array[i]), power--);

    }

    printf("\n Sum of the polynomial = %6.2f \n", polySum);

}


3)Data Structure Write a ‘C’ program to accept a string from user and
reverse it using Static

implementation of Stack.

Ans:

#include <stdio.h> #include <string.h> #define MAX 100 int
top=-1; int item; char stack_string[MAX]; void pushChar(char item); char
popChar(void); int isEmpty(void); int isFull(void); int main() { char
str[MAX]; int i; printf("Input a string: "); scanf("%[^\n]s",str);
for(i=0;i<strlen(str);i++) pushChar(str[i]);
for(i=0;i<strlen(str);i++) str[i]=popChar(); printf("Reversed String is:
%s\n",str); return 0; } void pushChar(char item) { if(isFull()) {
printf("\nStack is FULL !!!\n"); return; } top=top+1;
stack_string[top]=item; } char popChar() { if(isEmpty()) { printf("\nStack
is EMPTY!!!\n"); return 0; } item = stack_string[top];
    top=top-1;
    return item; } int isEmpty() { if(top==-1)
return 1; else return 0; } int isFull() { if(top==MAX-1) return 1; else
return 0; }

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

Ans:
#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; preptr->nextptr = newnode; preptr = newnode; } preptr->nextptr = stnode; } } void displayClList() { struct node* tmp; int n = 1; if (stnode == NULL) { printf("No data found in the List yet."); } else { tmp = stnode; printf("\n\nData 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)

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

struct node { int data; struct node* next; } *LLOne, *LLTwo, *unionLL, *intersectionLL; void initialize() { LLOne = LLTwo = NULL; } void insert(struct node** head, int num) { struct node* newNode = (struct node*)malloc(sizeof(struct node)); newNode->data = num; newNode->next = *head; *head = newNode; } int search(struct node* head, int num) { while (head != NULL) { if (head->data == num) { return 1; } head = head->next; } return 0; } struct node* findunion(struct node* LLOne, struct node* LLTwo) { unionLL = NULL; struct node* temp = LLOne; while (temp != NULL) { insert(&unionLL, temp->data); temp = temp->next; } while (LLTwo != NULL) { if (!search(LLOne, LLTwo->data)) { insert(&unionLL, LLTwo->data); } LLTwo = LLTwo->next; } return unionLL; } struct node* intersection(struct node* LLOne, struct node* LLTwo) { intersectionLL = NULL; while (LLOne != NULL) { if (search(LLTwo, LLOne->data)) { insert(&intersectionLL, LLOne->data); } LLOne = LLOne->next; } return intersectionLL; } void printLinkedList(struct node* nodePtr) { while (nodePtr != NULL) { printf("%d", nodePtr->data); nodePtr = nodePtr->next; if (nodePtr != NULL) printf("-->"); } } int main() { int i, LLOneCount, LLTwoCount, temp; initialize(); printf("Enter the number of nodes in the first Linked List: "); scanf("%d", &LLOneCount); printf("Enter %d integers: ", LLOneCount); for (i = 0; i < LLOneCount; i++) { scanf("%d", &temp); insert(&LLOne, temp); } printf("First Linked List: "); printLinkedList(LLOne); printf("\nEnter the number of nodes in the second Linked List: "); scanf("%d", &LLTwoCount); printf("Enter %d integers: ", LLTwoCount); for (i = 0; i < LLTwoCount; i++) { scanf("%d", &temp); insert(&LLTwo, temp); } printf("Second Linked List: "); printLinkedList(LLTwo); findunion(LLOne, LLTwo); intersection(LLOne, LLTwo); printf("\nUnion Linked List: "); printLinkedList(unionLL); printf("\nIntersection Linked List: "); printLinkedList(intersectionLL); return 0;
}



6) Write a ‘C’ program to read the adjacency matrix
of directed graph and convert it into adjacency list.

Ans:
#include<stdio.h>
#include<malloc.h>
struct n
{
int data;
struct n *link;
};
typedef struct n NODE;
NODE *getnode(int);
NODE *findlast(NODE *);
void display(NODE *[],int);
int main()
{
NODE *ptr,*temp,*h[10];
int n,a[10][10],i,j;
printf("\n Enter total number of vertices :");
scanf("%d",&n);
printf("\n Enter entries of an adjacency matrix :\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("\n Enter a[%d][%d] : ",i+1,j+1);
scanf("%d",&a[i][j]);
}
}
printf("\n Entered Adjacency matrix is … \n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
printf("\t %d ",a[i][j]);
}
printf("\n");
}
for(i=0;i<n;i++)
h[i]=NULL;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(a[i][j]==1)
{
temp=getnode(j+1);
if(h[i]==NULL)
h[i]=temp;
else
{
ptr=findlast(h[i]);
ptr->link=temp;
}
}
}
}
printf("\n The Adjacency list looks like … \n");
display(h,n);

}
NODE *getnode(int j)
{
NODE* temp;
temp =(NODE *) malloc(sizeof(NODE));
temp->data=j;
temp->link=NULL;
return(temp);
}
NODE *findlast(NODE *h)
{
NODE *ptr;
for(ptr=h;ptr->link!=NULL;ptr=ptr->link);
return(ptr);
}
void display(NODE *h[10],int n)
{
NODE *ptr;
int i;
for(i=0;i<n;i++)
{
printf("\n V%d ",i+1);
ptr=h[i];
if(ptr==NULL)
printf("NULL");
while(ptr!=NULL)
{
printf(" ->V%d",ptr->data);
ptr=ptr->link;
}
printf("\n");
}
}
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

Ans:
#include <stdlib.h>
#include<malloc.h>

struct node
 {
  
  struct node *left;
  int data ;
  struct node *right;
};


struct node *insert(struct node *p, int v)
{
if(p==NULL)
{
p=(struct node *) malloc(sizeof(struct node));
p -> left = p -> right = NULL;
p -> data = v;
}
else if (v<p->data) 
{
p->left=insert(p->left,v);
}
else if(v>p->data)
{
p->right=insert(p->right,v);
}
return (p);
}
void Inorder(struct node* p)
{
    if (p == NULL)
        return;
 
    Inorder(p->left);
 
    
    printf("%d ", p->data);
 
    
    Inorder(p->right);
}
void postorder (struct node *p)
 {
  if (p!=NULL) 
  {
  postorder (p -> left);
  postorder(p -> right);
  printf("%d \t", p-> data);
}
}
int main()
 {
int n,i,val;
struct node *tree=NULL,*temp=NULL;
printf("Enter How many nodes\t");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter value :");
scanf("%d",&val);
tree=insert(tree,val);
}
printf("\nInorder Traversal\n");
Inorder(tree);
printf("\npostorder Traversal\n");
postorder(tree);
}

8)Write a ‘C’ program to accept two polynomial and find the addition of accepted polynomials.(use array)
Ans:

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

struct poly
{
  float coeff;
  int exp;
};



struct poly a[50],b[50],c[50],d[50];

int main()
{
 int i;
 int deg1,deg2;      
 int k=0,l=0,m=0;
 
 
 printf("Enter the highest degree of poly1:");
 scanf("%d",&deg1);

 for(i=0;i<=deg1;i++)
 {
 
    
    printf("\nEnter the coeff of x^%d :",i);
    scanf("%f",&a[i].coeff);
a[k++].exp = i;
 }

 printf("\nEnter the highest degree of poly2:");
 scanf("%d",&deg2);
 
 for(i=0;i<=deg2;i++)
 { 
       printf("\nEnter the coeff of x^%d :",i);
       scanf("%f",&b[i].coeff);
   
   b[l++].exp = i;
 }

 

  printf("\nExpression 1 = %.1f",a[0].coeff);
  for(i=1;i<=deg1;i++)
  {
    printf("+ %.1fx^%d",a[i].coeff,a[i].exp);
  }    
  
  
  
  printf("\nExpression 2 = %.1f",b[0].coeff);
   for(i=1;i<=deg2;i++)
    {
      printf("+ %.1fx^%d",b[i].coeff,b[i].exp);
    }


 if(deg1>deg2)
    {
for(i=0;i<=deg2;i++)
  {
c[m].coeff = a[i].coeff + b[i].coeff;
c[m].exp = a[i].exp;
m++;
  }
  
  for(i=deg2+1;i<=deg1;i++)
  {
c[m].coeff = a[i].coeff;
c[m].exp = a[i].exp;
m++;
  }

    }
 else
  {
    for(i=0;i<=deg1;i++)
     {
       c[m].coeff = a[i].coeff + b[i].coeff;
       c[m].exp = a[i].exp;
       m++;
     }
    
for(i=deg1+1;i<=deg2;i++)
    {
      c[m].coeff = b[i].coeff;
      c[m].exp = b[i].exp;
      m++;
    }
  }
  
  printf("\nExpression after additon  = %.1f",c[0].coeff);
  for(i=1;i<m;i++)
  {
     printf("+ %.1fx^%d",c[i].coeff,c[i].exp);
   }  
 
  return 0;

}
                
9)Write a ‘C’ program to create linked list with given
number in which data part of each node contains individual digit of the number.
(Ex. Suppose the number is 368 then the nodes of linked list should contain 3, 6, 8)
Ans:
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
};
struct node *start=NULL,*temp=NULL;
int main()
{
int num,a[10],i,j;
printf("enter the number:-");
scanf("%d",&num);
i=0;
while(num>0)
{
a[i]=num%10;
i++;
num=num/10;
}
i--;
printf("\nthe display of linked list is:-\n");
for(j=i;j>=0;j--)
{
if(start==NULL)
{
start=malloc(sizeof(struct node));
start->data=a[j];
printf("%d",start->data);
start->next=NULL;
temp=start;
}
else
{
temp->next=malloc(sizeof(struct node));
temp->next->data=a[j];
printf(",%d",temp->next->data);
temp->next->next=NULL;
temp=temp->next;
}
}
getch();
}


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

Ans:
#include <stdio.h>
void bubble_sort(long [], long);

int main()
{
  long array[100], n, c;

  printf("Enter number of elements\n");
  scanf("%ld", &n);

  printf("Enter %ld integers\n", n);

  for (c = 0; c < n; c++)
    scanf("%ld", &array[c]);

  bubble_sort(array, n);

  printf("Sorted list in ascending order:\n");

  for (c = 0; c < n; c++)
     printf("%ld\n", array[c]);

  return 0;
}

void bubble_sort(long list[], long n)
{
  long c, d, t;

  for (c = 0 ; c < n - 1; c++) {
    for (d = 0 ; d < n - c - 1; d++) {
      if (list[d] > list[d+1]) {
        
        t         = list[d];
        list[d]   = list[d+1];
        list[d+1] = t;
      }
    }
  }
}


11)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.

Ans:

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


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

void createNodeList(int n);     
int NodeCount();             
void displayList();             

int main()
{
    int n,totalNode;
printf("\n\n Linked List : Create a singly linked list and count the number of nodes :\n");
printf("------------------------------------------------------------------------------\n");
    printf(" Input the number of nodes : ");
    scanf("%d", &n);
    createNodeList(n);
    printf("\n Data entered in the list are : \n");
    displayList();
    totalNode = NodeCount();
    printf("\n Total number of nodes = %d\n", totalNode);
    return 0;
}
void createNodeList(int n)
{
    struct node *fnNode, *tmp;
    int num, i;
    stnode = (struct node *)malloc(sizeof(struct node));
    if(stnode == NULL) 
    {
        printf(" Memory can not be allocated.");
    }
    else
    {

        printf(" Input data for node 1 : ");
        scanf("%d", &num);
        stnode-> num = num;      
        stnode-> nextptr = NULL; 
        tmp = stnode;

        for(i=2; i<=n; i++)
        {
            fnNode = (struct node *)malloc(sizeof(struct node));
            if(fnNode == NULL) 
            {
                printf(" Memory can not be allocated.");
                break;
            }
            else
            {
                printf(" Input data for node %d : ", i);
                scanf(" %d", &num);
                fnNode->num = num;      
                fnNode->nextptr = NULL; 
                tmp->nextptr = fnNode; 
                tmp = tmp->nextptr;
            }
        }
    }

int NodeCount()
{
    int ctr = 0;
    struct node *tmp;
    tmp = stnode;
    while(tmp != NULL)
    {
        ctr++;
        tmp = tmp->nextptr;
    }
    return ctr;
}
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);  
            tmp = tmp->nextptr;               
        }
    }



12)Write a ‘C’ program to accept and sort n elements in ascending order by using insertion sort.
Ans:
#include<stdio.h>
#define MAX 20
void insertionsort(int A[MAX], int n)
{
int i, j, key ;
for(i=1; i<n; i++)
{
key =A[i];
for(j=i-1;(j>=0)&&(key < A[j]);j--)
A[j+1] = A[j];
A[j+1] =key;
}
}
int main()
{
int A[MAX],i,n;
printf("How many elements you want to sort ?\n");
scanf("%d",&n);
printf("\nEnter the element into an arry:\n");
for(i=0;i < n; i++)
scanf("%d",&A[i]);
insertionsort (A,n);
printf("\nElements is Asending sort:\n");
for(i =0; i<n; i++)
printf("%d\t",A[i]);
}




13) 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

Ans:
#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;
}


14)Write a ‘C’ program to create a singly linked list, reverse it and display both the list.

Ans:
#include<stdio.h>
#include<conio.h>
#include <malloc.h>
struct list
{
int data;
struct list *link;
}*start;
void createlist(int);
void disp();
void main()
{
struct list *p1,*p2,*p3;
int i,n,m;
printf("\nHow many nodes u Want to Created");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\nEnter the Data");
scanf("%d",&m);
createlist(m);
}
printf("\n\nCreated List Is\n\n");
disp();
printf("\n\nReverses List is\n\n");
p1=start;
p2=p1->link;
p3=p2->link;
p1->link=NULL;
p2->link=p1;
while(p3!=NULL)
{
p1=p2;
p2=p3;
p3=p3->link;
p2->link=p1;
}
start=p2;
disp();
}
void createlist(int m)
{
struct list *tmp,*q;
tmp=(struct list *) malloc(sizeof(struct list));
tmp->data=m;
tmp->link=NULL;
if(start==NULL)
start=tmp;
else
{
q=start;
while(q->link!=NULL)
{
q=q->link;
}
q->link=tmp;
}
}
void disp()
{
struct list *q;
q=start;
while(q!=NULL)
{
printf("%d->",q->data);
q=q->link;
}
printf("NULL");
}

 


15)Write a ‘C’ program to read ‘n’ integers and store them in a
 Binary search tree and display the nodes level wise.

ANS:

#include<stdio.h>
#include<stdlib.h>
    struct node
{
    int key;
    struct node *left, *right;
};
    
struct node *newNode(int item)
{
    struct node *temp =  (struct node *)malloc(sizeof(struct node));
    temp->key = item;
    temp->left = temp->right = NULL;
    return temp;
}
    
void inorder(struct node *root)
{
    if (root != NULL)
    {
        inorder(root->left);
        printf("%d \n", root->key);
        inorder(root->right);
    }
}
    
struct node* insert(struct node* node, int key)
{
    
    if (node == NULL) return newNode(key);
  
    
    if (key < node->key)
        node->left  = insert(node->left, key);
    else if (key > node->key)
        node->right = insert(node->right, key);   
       
    return node;
}
    
int main()
{
    
    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);
        
    inorder(root);
        return 0;
}



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


Ans:
#include<stdio.h>
int main()
{

   
   int i, j, count, temp, number[25];

   printf("How many numbers u are going to enter?: ");
   scanf("%d",&count);

   printf("Enter %d elements: ", count);
   
   for(i=0;i<count;i++)
      scanf("%d",&number[i]);

   
   for(i=1;i<count;i++){
      temp=number[i];
      j=i-1;
      while((temp<number[j])&&(j>=0)){
         number[j+1]=number[j];
         j=j-1;
      }
      number[j+1]=temp;
   }

   printf("Order of Sorted elements: ");
   for(i=0;i<count;i++)
      printf(" %d",number[i]);

   return 0;
}






17)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

Ans:


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

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

void createNodeList(int n);     
void NodeInsertatEnd(int num);
void ser();
void displayList();             
 
int main()
{
    int n,num,m;
printf("\n\n Linked List : Insert a new node at the end of a Singly Linked List :\n");
printf("-------------------------------------------------------------------------\n");
    printf(" Input the number of nodes : ");
    scanf("%d", &n);
    createNodeList(n);
    printf("\n Data entered in the list are : \n");
    displayList();
    printf("\n Input data to insert at the end of the list : ");
    scanf("%d", &num);
    NodeInsertatEnd(num);
    printf("\n Data, after inserted in the list are : \n");
    ser();
    
    displayList();
    printf("\nENTER THE ELEMENT FOR SEARCH: ");
scanf("\n%d",&m);
ser(m);
displayList();
    
    return 0;
    
}
void createNodeList(int n)
{
    struct node *fnNode, *tmp;
    int num, i;
    stnode = (struct node *)malloc(sizeof(struct node));
    if(stnode == NULL) 
    {
        printf(" Memory can not be allocated.");
    }
    else
    {

        printf(" Input data for node 1 : ");
        scanf("%d", &num);
 
        stnode-> num = num;      
        stnode-> nextptr = NULL; 
        tmp = stnode;

        for(i=2; i<=n; i++)
        {
            fnNode = (struct node *)malloc(sizeof(struct node));
            if(fnNode == NULL) 
            {
                printf(" Memory can not be allocated.");
                break;
            }
            else
            {
                printf(" Input data for node %d : ", i);
                scanf(" %d", &num);
                fnNode->num = num;     
                fnNode->nextptr = NULL; 
                tmp->nextptr = fnNode; 
                tmp = tmp->nextptr;
            }
        }
    }

void NodeInsertatEnd(int num)
{
    struct node *fnNode, *tmp;
    fnNode = (struct node*)malloc(sizeof(struct node));
    if(fnNode == NULL)
    {
        printf(" Memory can not be allocated.");
    }
    else
    {
        fnNode->num = num;     
        fnNode->nextptr = NULL; 
        tmp = stnode;
        while(tmp->nextptr != NULL)
            tmp = tmp->nextptr;
        tmp->nextptr = fnNode;
    }
}

void ser(int num)
 
 {
struct node *q,*tmp;
q=stnode;
while(q!=NULL)
{
if(q->num==num)
{
printf("\nElement Is Found");
break;
}
else
{
q=q->nextptr;
}
}
if(q==NULL)
{
printf("\nElement is Not Found");
}
}

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





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

Ans:

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct queue
{
int data;
struct queue *next;
}*front,*rear;
int insertQ(int n)
{
struct queue *temp;
temp =(struct queue *)malloc(sizeof(struct queue));
temp->data =n;
temp->next =NULL;
if(front == NULL)
rear=front=temp;
else
{
rear->next=temp;
rear=temp;
}
}
int deleteQ()
{
int x;
struct queue *temp=front;
x=front->data;
if(front==rear)
front=rear=NULL;
else
front=front->next;
free(temp);
return(x);
}
int display()
{
struct queue *temp=front;
printf("\nQuene contents are:\t");
while(temp)
{
printf("%d\t",temp->data);
temp =temp ->next;
}
}
int  main()
{
int ch,x;
do{
printf("\n 1-Insert \n2-Delete\n3-Display\n4-Exit\n");
printf("Enter  youre choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1: printf("Enter element to be insert \n");
scanf("%d",&x);
insertQ(x);
display();
break;
case 2 :if(front == NULL)
printf("Queue is Empty\n");
else{
printf("Deleted element is %d\n",deleteQ());
display();
break;
case 3: 
display();
break;
case 4 :
exit(1);
break;
}
}
}while(ch>0 && ch<5);
return 0;
}








19) 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 vertic
Ans:



#include<stdio.h>
#include<stdlib.h>
int n,g[10][10];
void inoutdegree()
int i,j,id=0,od=0;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
od+=g[i][j];
id+=g[j][i];
}
printf("v%d indegree =%d \t Outdegree= %d\n",i,id,od);
}
}
 main()
int i,j,cnt=0;
printf("How many vertices");
scanf("%d",&n);
printf("Enter matrix elements\n");
for(i=0;i<n;i++)
{
  for(j=0;j<n;j++)
scanf("%d",&g[i][j]);
}
}
printf("Adjacency matrix Is\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(g[i][j]!=g[j][i])
cnt++;
printf("%d\t",g[i][j]);
}
printf("\n");
}
}




20) Write a ‘C’ program to accept and sort n elements in
ascending order using Selection sort method
Ans:

#include<stdio.h>
int main()
{
int array[100],n,i,j,position,t;
printf("Enter number of Elements\n");
scanf("%d",&n);
printf("Enter %d integers\n",n);
for(i=0;i<n;i++)
scanf("%d",&array[i]);
for(i=0;i<(n-1);i++)
{
position=i;
for(j=i+1;j<n;j++)
{
if(array[position]>array[j])
position=j;
}
if(position!=i)
{
t=array[i];
array[i]=array[position];
array[position]=t;
}
}
printf("Sorted list in ascending order:\n");
for(i=0;i<n;i++)
printf("%d\n",array[i]);
return 0;
}



21) Write a ‘C’ program to accept a string from
user and reverse it using Dynamic implementation of Stack.
Ans:


//Write a ‘C’ program to accept a string from user and reverse it using Dynamic implementation of Stack.
#include<stdio.h>
#include<string.h>
struct Stack{
char arr[100];
int tos;
};
void push(struct Stack*,char);
char pop(struct Stack*);
int main()
{
struct Stack s;
s.tos=-1;
char str[100];
printf("Enter string reverse:\n");
scanf("%s",&str);
int i;
for(i=0;i<strlen(str);i++)
{
push(&s,str[i]);
}
for(i=0;i<strlen(str);i++)
{
str[i]=pop(&s);
}
printf("After reversing string:  %s",str);
return 0;
}
void push(struct Stack *p,char x){
if(p->tos==99){
printf("Stack is OverFolw");
return;
}
else{
p->tos=p->tos+1;
p->arr[p->tos]=x;
}
}
char pop(struct Stack* p){
if(p->tos==-1){
return 0;
}
else{
int x=p->arr[p->tos];
p->tos=p->tos-1;
return x;
}
}

22)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



Ans:
#include <stdio.h>
#include <string.h>
int  main()
{
  char name[25][50],temp[25];
  int n,i,j;
  
       printf("\n\nSorts the strings of an array using bubble sort :\n");
       printf("-----------------------------------------------------\n");  
  
 
  printf("Input number of strings :");
  scanf("%d",&n);

printf("Input string %d :\n",n);
  for(i=0;i<=n;i++)
  {
       
       fgets(name[i], sizeof name, stdin);
  }
    

     for(i=1;i<=n;i++)
for(j=0;j<=n-i;j++)
  if(strcmp(name[j],name[j+1])>0)
  { 
            strcpy(temp,name[j]);
    strcpy(name[j],name[j+1]);
    strcpy(name[j+1],temp);
  }
   printf("The strings appears after sorting :\n");
      for(i=0;i<=n;i++)
printf("%s\n",name[i]);
 



23) Write a ‘C’ program to accept an infix expression,
convert it into its equivalent postfix expression and 
display the result.(Use Dynamic Implementation of Stack)


Ans:
#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;
}



24)Write menu driven program using ‘C’ for Dynamic implementation of Stack.
 The menu includes following operations:
- Push
- Pop
- Display
- Exit
Ans:

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
struct Node
{
int data;
struct Node *next;
}*top;
void push(int value)
{
struct Node *newNode;
newNode= (struct Node*)malloc(sizeof(struct Node));
newNode->data=value;
newNode->next=NULL;
if(top == NULL)
top=newNode;
else
{
newNode->next =top;
top=newNode;
}
printf("\nInsertion is Success!!!\n");
}
void pop()
{
if(top==NULL)
printf("\nStack is Empty!!!\n");
else{
struct Node *temp=top;
top=top->next;
printf("\nDeleted element : %d",temp->data);
free(temp);
}
}
void display()
{
if(top==NULL)
printf("\nStack is Empty!!!\n");
else
{
struct Node *temp=top;
while(temp!=NULL)
{
printf("%d---->",temp->data);
temp=temp->next;
}
printf("----->NULL");
}
}
int main()
{
int choice,value;
printf("\n::Stack  using Linked List::\n");
while(1)
{
printf("\n#########MENU########\n");
printf("1.Push\n2.Pop\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);
push(value);
break;
case 2:pop();break;
case 3:display();break;
case 4:exit(0);
default:printf("\nWrong selection !!!Please try again!!!\n");
}
}
}



25)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

Ans:
#include<stdio.h>
#include <stdlib.h>
#include<malloc.h>

struct node
 {
 
  struct node *left;
  int data ;
  struct node *right;
};


struct node *insert(int v)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
    node->data = v;
    node->left = NULL;
    node->right = NULL;
 
    return (node);
}
void Preorder(struct node *p)
{
    if (p!= NULL)
    {
   printf("\t%d ", p->data);
    Preorder(p->left);
    Preorder(p->right);
}
}
void Inorder(struct node *p)
{
    if (p == NULL)
        return;
 
    Inorder(p->left);
 
    printf("%d ", p->data);
 
     Inorder(p->right);
}

void Postorder (struct node *p)
{
  if (p!=NULL)
  {
  Postorder (p->left);
  Postorder(p->right);
  printf("%d \t", p-> data);
}
}

int main()
 {
struct node* root = insert(1);
    root->left = insert(2);
    root->right = insert(3);
    root->left->left = insert(4);
    root->left->right = insert(5);

printf("\npreorder Traversal\n");
Preorder(root);

printf("\nInorder Traversal\n");
Inorder(root);
printf("\npostorder Traversal\n");
Postorder(root);
}















Post a Comment

6 Comments

Please do not enter any spam link in the comment box.