Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
23 views

C With Data Structures 7-14

Uploaded by

ARIF K F
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

C With Data Structures 7-14

Uploaded by

ARIF K F
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

07.Write a recursive program to find GCD of 4,6,8.

GCD(x, y)
Begin
if y = 0 then
return x;
else if(y>x)
Call: GCD(y,x);
else
Call: GCD(y, x%y);
endif
End
#include<stdio.h>
int gcd(int m,int n)
{
if(n==0)
return m;
else if(n>m)
gcd(n,m);
else
gcd(n,m%n);
}

void main()
{
int a,b,c,n1,n2;
printf("Input Numbers: ");
scanf("%d%d%d",&a,&b,&c);
n1=gcd(a,b);
n2=gcd(n1,c);
printf("\nGCD of %d,%d and %d is %d",a,b,c,n2);
}

Output:
Input Numbers: 4 6 8

GCD of 4,6 and 8 is 2

08.Write a program to insert the elements {5,7,0,6,3,9} into circular queue and delete
5,7,0,6 from it(using linked list implementation).

void ENQUEUE()
Step1: Create a newNode with the given value and set the node's pointer to NULL.
Step2: Check whether the queue is EMPTY.
Step3: If it is EMPTY, set FRONT and REAR to newNode.
Step4: Else, set the pointer of REAR to newNode and make REAR as the newNode.

void DEQUEUE()
Step1: Check if the queue is EMPTY.
Step2: If it is EMPTY, then display "EMPTY QUEUE" and exit.
Step3:Else, create a temporary node and set it to FRONT.
Step4: Make the next node as FRONT and delete the temporary node.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node *f = NULL;
struct node *r = NULL;
void enqueue(int d)
{
struct node* n;
n = (struct node*)malloc(sizeof(struct node));
n->data = d;
n->next = NULL;
if((r==NULL)&&(f==NULL))
{
f = r = n;
r->next = f;
}
else
{
r->next = n;
r = n;
n->next = f;
}
}
void dequeue()
{
struct node* t;
t = f;
if((f==NULL)&&(r==NULL))
printf("\nQueue is Empty");
else if(f == r){
f = r = NULL;
printf("\n%d is deleted",t->data);
free(t);
}
else{
f = f->next;
r->next = f;
printf("\n%d is deleted",t->data);
free(t);
}

}
void display()
{

struct node* t;
t = f;
if((f==NULL)&&(r==NULL))
printf("\nQueue is Empty");
else{
do{
printf("\n%d",t->data);
t = t->next;
}while(t != f);
}
}
void main()
{
int ch,n,i,data;
printf("\n\n1.Enqueue\n2.Dequeue \n3.Display\n4.Exit");
do{

printf("\nEnter Your Choice: ");


scanf("%d",&ch);
switch(ch){
case 1: printf("\nEnter your data: ");
scanf("%d",&data);
enqueue(data);
break;
case 2: dequeue();
break;
case 3: display();
break;
case 4: break;
default:printf("\nInvalid Choice");

}
}while(ch!=4);

Output:
1.Enqueue
2.Dequeue
3.Display
4.Exit
Enter Your Choice: 1
Enter your data: 5

Enter Your Choice: 1


Enter your data: 7

Enter Your Choice: 1


Enter your data: 0

Enter Your Choice: 1


Enter your data: 6

Enter Your Choice: 1


Enter your data: 3

Enter Your Choice: 1


Enter your data: 9

Enter Your Choice: 3

5
7
0
6
3
9
Enter Your Choice: 2

5 is deleted
Enter Your Choice: 2

7 is deleted
Enter Your Choice: 2

0 is deleted
Enter Your Choice: 2

6 is deleted
Enter Your Choice: 3

3
9
Enter Your Choice: 4

09.Given s1={Flowers}; s2={are beautiful},


(a). Find the length of s1
(b). Concatenate s1 and s2
(c). Extract the substring “low” from s1
(d). Find “are” in s2 and replace it with “is”.

int LENGTHSTR(char[] ch)


Step1: while ch!=NULL perform Step2
Step2: Increment count
Step3: return count
Step4: Exit

void CONCATSTR(char[] s1,char[] s2)


Step1: while s1!=NULL perform Step2
Step2: Copy s1 to s
Step3: while s2!=NULL perform Step4
Step4: Copy s2 to s
Step5: Print s
Step6: Exit

void SUBSTRING(char ch[],int x,int y)


Step1: while x<=y perform Step2
Step2: Copy ch to s, Increment x
Step3: Print s
Step4: Exit

void REPLACE(char[] ch,char[] old,char[] new)


Step1: Check if the old is present in the ch or not
Step2: If the old is not present in the ch, terminate the program.
Step3: If the old is present in the main ch then continue.
Step4: Iterate each character of the ch
Step5: Replace the old with the new.
Step6: Print new
Step7: Exit
#include<stdio.h>
#include<string.h>

int lengthstr(char ch[])


{
int len,i=0,count=0;
while(ch[i]!='\0')
{
count++;
i++;
}

return count;
}

void concatestr(char s1[],char s2[])


{
int len1=lengthstr(s1);
int len2=lengthstr(s2);
char s[100];int i=0,j=0;
while(s1[j]!='\0')
{
s[i]=s1[j] ;
j++;i++;
}
j=0;
while(s2[j]!='\0')
{
s[i]=s2[j];
j++;i++;
}
s[i]='\0';
printf("\nConcatenated string is %s",s);
}

void substring(char ch[],int x1,int x2)


{
int i=x1;char s[20];int j=0;
if(x1<lengthstr(ch)&&x2<lengthstr(ch)&&x1<x2)
{
while(i<=x2)
{
s[j]=ch[i];
j++;i++;
}
s[j]='\0';
printf("\nSubstring of %s from index %d to %d is %s",ch,x1,x2,s);
}
else if(x2>lengthstr(ch))
printf("\nIndex is more than the string length");
else if(x1>lengthstr(ch))
printf("\nStarting index must be less than string length");
else if(x1>x2)
printf("\nStarting index must less than end index");
}

void replace()
{
char s[20],s1[20],old[20],new[20];
printf("\nEnter the string: ");
gets(s1);
printf("\nEnter the substring to be replaced : ");
gets(old);
printf("\nEnter replacement string: ");
gets(new);
int slen=lengthstr(s1);
int len1=lengthstr(old);
int len2=lengthstr(new);

strcpy(s,s1);
int i=0,j,k,flag=0,start,end;
for(i=0;i<slen;i++)
{
flag=0;
start=i;
for(j=0;s[i]==old[j];j++,i++)
if(j==len1-1)
flag=1;
end=i;
if(flag==0)
i-=j;
else
{
for(j=start;j<end;j++)
{
for(k=start;k<slen;k++)
s[k]=s[k+1];
slen--;
i--;
}

for(j=start;j<start+len2;j++)
{
for(k=slen;k>=j;k--)
s[k+1]=s[k];
s[j]=new[j-start];
slen++;
i++;
}
}
}
if(strcmp(s1,s))
printf("\n%s is replaced in %s with %s :%s ",old,s1,new,s);
else
printf("\n%s is not substring of %s",old,s1);
}

void main()
{
char s1[20],s2[20],s[20];
printf("Enter first string: ");
gets(s1);
printf("Enter second string: ");
gets(s2);
printf("\nLength of %s is %d",s1,lengthstr(s1));
printf("\nLength of %s is %d",s2,lengthstr(s2));
concatestr(s1,s2);
replace();
printf("\nEnter string to which find substring: ");
gets(s1);
int x1,x2;
printf("\nEnter start and end index of substring in string: ");
scanf("%d%d",&x1,&x2);
substring(s1,x1,x2);

Output:

Enter first string: Flowers


Enter second string: are beautiful

Length of Flowers is 7
Length of are beautiful is 14
Concatenated string is Flowers are beautiful
Enter the string: are beautiful

Enter the substring to be replaced : are

Enter replacement string: is

are is replaced in are beautiful with is :is beautiful


Enter string to which find substring: Flowers

Enter start and end index of substring in string: 1 3

Substring of Flowers from index 1 to 3 is low

10.Write a program to convert an infix expression x^y/(5*z)+2 to its postfix expression.

Step1: Initialize the Stack.


Step2: Scan the operator from left to right in the infix expression.
Step3: If the leftmost character is an operand, set it as the current output to the Postfix string.
Step4: And if the scanned character is the operator and the Stack is empty or contains the '(',
')' symbol, push the operator into the Stack.
Step5: If the scanned operator has higher precedence than the existing precedence operator
in the Stack or if the Stack is empty, put it on the Stack.
Step6: If the scanned operator has lower precedence than the existing operator in the Stack,
pop all the Stack operators. After that, push the scanned operator into the Stack.
Step7: If the scanned character is a left bracket '(', push it into the Stack.
Step8: If we encountered the right bracket ')', pop the Stack and print all output string
character until '(' is encountered and discard both the brackets.
Step9: Repeat all steps from 2 to 8 until the infix expression is scanned.
Step10: Print the Stack output.
Step11: Pop and output all characters, including the operator, from the Stack until it is not
empty.
#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;
if(x=='^')
return 3;
return 0;
}

void main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
e = exp;
printf("Postfix expressio: ");
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());
}
}

Output:
Enter the expression : x^y/(5*z)+2

Postfix expression: x y ^ 5 z * / 2 +

11.Write a program to evaluate a postfix expression 5 3+8 2-*.

Step 1: If a character is an operand push it to Stack


Step 2: If the character is an operator
Pop two elements from the Stack.
Operate on these elements according to the operator, and push the result back to the Stack
Step 3: Step 1 and 2 will be repeated until the end has reached.
Step 4: The Result is stored at the top of the Stack,
return it
Step 5: End
#include<stdio.h>
#include<ctype.h>
#include<math.h>
int stack[10];
int top=-1;
void push(int );
int pop();
int exp_eval(char[]);
void main()
{
int j=0;
char exp[20];
int res;
printf("Enter a postfix expression: ");
gets(exp);
res=exp_eval(exp);
printf("The result of %s = %d",exp,res);

int exp_eval(char exp[])


{
int i;
int num=0;
for(i=0;exp[i];++i)
{
if(exp[i]==' ')
{
continue;
}
else if(isdigit(exp[i]))
{
num=0;
while(isdigit(exp[i]))
{
num=num*10+(int)(exp[i]-'0');
i++;
}
i--;
push(num);
}
else{
int opB=pop();
int opA=pop();
switch(exp[i])

{
case '+': push(opA+opB);break;
case '-': push(opA-opB);break;
case '*': push(opA*opB);break;
case '/': push(opA/opB);break;
case '^': push(pow(opA,opB));break;
}
}
}
return pop();
}

void push(int ch)


{
top=++top;
stack[top]=ch;
}
int pop()
{
int n;
n=stack[top];
top=--top;
return n;
}

Output:

Enter a postfix expression: 5 3+8 2-*


The result of 5 3+8 2-* = 48

12.Write a program to create a binary tree with the elements 18,15,40,50,30,17,41 after
creation insert 45 and 19 into tree and delete 15,17 and 41 from tree.Display the tree on
each insertion and deletion operations.

struct node *newnode(int item)


Step1: Allocate memory for newnode
Step2: Set newnode->data=item,newnode->left=NULL,newnode->right=NULL
Step3: return newnode;
Step4: Exit

struct node *insert(struct node *node,int data)


Step1: if(node==NULL) then
Step2: return newnode(data) go to Step5
Step3: if(data<node->data) then
a.node->left=insert(node->left,data)
else
b.node->right=insert(node->right,data)
Step4: return node
Step5: Exit

struct node *Delete(struct node *node)


Step1: struct node *pos=node
Step2: Repeat Step3 to Step4 while(pos&&pos->left!=NULL)
Step3: pos=pos->left
Step4: return pos
Step5: Exit

struct node *deletenode(struct node *root,int data)


Step1: if(root==NULL) then
Step2: return root go to Step
Step3: if(data<root->data) then
a.root->left=deletenode(root->left, data)
else if(data>root->data)
b.root->right=deletenode(root->right,data)
else
c.if(root->left==NULL)
i.struct node *temp=root->right
ii.free(root)
iii.return temp
d.else if(root->right==NULL)
i.struct node *temp=root->left
ii.free(root)
iii.return temp
[End if]
e.struct node *temp=Delete(root->right)
f.root->data=temp->data
g.root->right=deletenode(root->right,temp->data)
[End if]
Step4: return root
Step5: Exit
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *left;
struct node *right;
};
struct node *newnode(int item)
{
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=item;
newnode->left=NULL;
newnode->right=NULL;
return newnode;
}
void inorder(struct node *root)
{
if(root!=NULL)
{
inorder(root->left);
printf("\t%d",root->data);
inorder(root->right);
}
}
struct node *insert(struct node *node,int data)
{
if(node==NULL)
return newnode(data);
if(data<node->data)
node->left=insert(node->left,data);
else
node->right=insert(node->right,data);
return node;
}
struct node *Delete(struct node *node)
{
struct node *pos=node;
while(pos&&pos->left!=NULL)
pos=pos->left;
return pos;
}
struct node *deletenode(struct node *root,int data)
{
if(root==NULL)
return root;
if(data<root->data)
root->left=deletenode(root->left, data);
else if(data>root->data)
root->right=deletenode(root->right,data);
else
{
if(root->left==NULL)
{
struct node *temp=root->right;
free(root);
return temp;
}
else if(root->right==NULL)
{
struct node *temp=root->left;
free(root);
return temp;
}
struct node *temp=Delete(root->right);
root->data=temp->data;
root->right=deletenode(root->right,temp->data);
}
return root;
}

int main()
{
struct node *root=NULL;
root=insert(root,18);
root=insert(root,15);
root=insert(root,40);
root=insert(root,50);
root=insert(root,30);
root=insert(root,17);
root=insert(root,41);
printf("\nelements in creation are:\n");
inorder(root);
root=insert(root,45);
root=insert(root,19);
printf("\nafter inserting 45 and 19 \n");
inorder(root);
root=deletenode(root,15);
printf("\nafter deleting 15\n");
inorder(root);
root=deletenode(root,17);
printf("\nafter deleting 17\n");
inorder(root);
root=deletenode(root,41);
printf("\nafter deleting 41\n");
inorder(root);
}

Output:

Elements in tree after insertion:


15 17 18 30 40 41 50
Elements in tree after insertion of 45 and 19:
15 17 18 19 30 40 41 45 50
Elements in tree after deleting 15:
17 18 19 30 40 41 45 50
Elements in tree after deleting 17:
18 19 30 40 41 45 50
Elements in tree after deleting 41:
18 19 30 40 45 50

13.Write a program to create a binary search tree with the elements {2,5,1,3,9,0,6} and
perform inorder,preorder and postorder traversal.

insert(node* root,int item)


Step1: if root=NULL then
a. Allocate memory for root
b. Set root->data=item
c. Set root->left=root->right=NULL
else if item<root->data then
insert(root->left,item)
else
insert(root->right,item)
[End if]
Step2: Exit

void inorder(node* root)


Step1: Repeat Step2 to Step4 while root!=NULL
Step2: inorder(root->left)
Step3: print root->data
Step4: inorder(root->right)
Step5: Exit

void preorder(node* root)


Step1: Repeat Step2 to Step4 while root!=NULL
Step2: print root>data
Step3: preorder(root->right)
Step4: preorder(root->right)
Step5: Exit

void postorder(node* root)


Step1: Repeat Step2 to Step4 while root!=NULL
Step2: postorder(root->left)
Step3: postorder(root->right)
Step4: print root->data
Step5: Exit
#include<stdio.h>
#include<stdlib.h>
typedef struct BST
{
int data;
struct BST* left;
struct BST* right;
}node;

node* create();
void insert(node*,node*);
void preorder(node*);
void postorder(node*);
void inorder(node*);

int main()
{
char ch;
node* root=NULL,*temp;
do
{
temp=create();
if(root==NULL)
root=temp;
else
insert(root,temp);
printf("Do you want to enter more(Y/N)?: ");
getchar();
scanf("%c",&ch);
}while(ch=='y'||ch=='Y');
printf("Preorder Traversal: \n");
preorder(root);
printf("\nPostorder Traversal: \n");
postorder(root);
printf("\nInorder Traversal: \n");
inorder(root);
return 0;
}

node* create()
{
node* temp;
printf("\nEnter data: ");
temp=(node*)malloc(sizeof(node));
scanf("%d",&temp->data);
temp->left=temp->right=NULL;
return temp;
}

void insert(node* root,node* temp)


{
if(temp->data<root->data)
{
if(root->left!=NULL)
insert(root->left,temp);
else
root->left=temp;
}
if(temp->data>root->data)
{
if(root->right!=NULL)
insert(root->right,temp);
else
root->right=temp;
}
}

void preorder(node* root)


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

void postorder(node* root)


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

void inorder(node* root)


{
if(root!=NULL)
{
inorder(root->left);
printf("%d ",root->data);
inorder(root->right);

}
}

Output:

Enter data: 2
Do you want to enter more(Y/N)?: y

Enter data: 5
Do you want to enter more(Y/N)?: y

Enter data: 1
Do you want to enter more(Y/N)?: y

Enter data: 3
Do you want to enter more(Y/N)?: y

Enter data: 9
Do you want to enter more(Y/N)?: y

Enter data: 0
Do you want to enter more(Y/N)?: y

Enter data: 6
Do you want to enter more(Y/N)?: n
Preorder Traversal:
2 1 0 5 3 9 6
Postorder Traversal:
0 1 3 6 9 5 2
Inorder Traversal:
0 1 2 3 5 6 9

14.Write a program to sort the following elements using heap sort {9,16,32,8,4,1,5,8,0}.

void HeapSort(arr)
BuildMaxHeap(arr)
for i = length(arr) to 2
swap arr[1] with arr[i]
heap_size[arr] = heap_size[arr] ? 1
MaxHeapify(arr,1)
End

void BuildMaxHeap(arr)
heap_size(arr) = length(arr)
for i = length(arr)/2 to 1
MaxHeapify(arr,i)
End

void MaxHeapify(arr,i)
L = left(i)
R = right(i)
if L ? heap_size[arr] and arr[L] > arr[i]
largest = L
else
largest = i
if R ? heap_size[arr] and arr[R] > arr[largest]
largest = R
if largest != i
swap arr[i] with arr[largest]
MaxHeapify(arr,largest)
End
#include<stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}
void heapify(int arr[], int n, int i) {

int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}

void heapSort(int arr[], int n) {


int i;

for (i = n / 2 - 1; i >= 0; i--)


heapify(arr, n, i);

for (i = n - 1; i >= 0; i--) {


swap(&arr[0], &arr[i]);

heapify(arr, i, 0);
}
}

void printArray(int arr[], int n) {


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

int main() {
int arr[] = {9,16,32,8,4,1,5,8,0};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array before sorting is \n");
printArray(arr, n);
heapSort(arr, n);

printf("Sorted array is \n");


printArray(arr, n);
}

Output:

Array before sorting is


9 16 32 8 4 1 5 8 0
Sorted array is
0 1 4 5 8 8 9 16 32

You might also like