Cs3362 C Programming and Data Structures Lab Ece
Cs3362 C Programming and Data Structures Lab Ece
Cs3362 C Programming and Data Structures Lab Ece
AIM:
ALGORITHM:
Area->integer
Radius->integer
Step 4: Calculate
Step 6: Stop.
1
C PROGRAM:
/*Area of Circle*/
#include<stdio.h>
#include<conio.h
> void main()
{
float r,area;
clrscr();
printf("Enter the Radius of the circle:\n");
printf("\nRadius=");
scanf("%f",&r);
area=3.14*r*r;
printf("\n Area=%f",area);
getch();
}
OUTPUT :
Radius=5
Area=78.500000
RESULT:
Thus the area of the circle using C program has been executed and verified successfully.
2
EX.NO 1B) TO FIND THE GIVEN NUMBER IS EVEN OR ODD
AIM:
ALGORITHM:
3
C PROGRAM:
#include<stdio.h>
#include<conio.h
> void main()
{
int n;
clrscr();
printf("Enter the number:");
scanf("%d",&n); if(n
%2==0)
{
printf("\n The number %d is Even..!",n);
}
else
{
printf("\n The number %d is Odd..!",n);
}
getch();
}
4
OUTPUT:
RESULT:
Thus the given number is even or odd using C program has been executed and verified successfully.
5
EX.NO:1C) AVERAGE OF FIVE
MARKS AIM:
ALGORITHM:
6
C PROGRAM:
#include<stdio.h>
#include<conio.h
> void main()
{
int m1,m2,m3,m4,m5;
clrscr();
floatavg,tot;
printf("Enter the 5 marks\n"); scanf("%d%d%d%d
%d",&m1,&m2,&m3,&m4,&m5);
tot=m1+m2+m3+m4+m5;
avg=tot/5;
printf("\n The average is %f\n",avg);
getch();
}
OUTPUT:
Enter the 5
marks 99
35
65
78
35
The average is 62.400002
RESULT:
Thus the average of five numbers using C program has been executed and verified successfully.
AIM:
7
To write a program to generate fibonocci series
ALGORITHM:
C PROGRAM:
#include<stdio.h>
#include<conio.h>
8
void main()
{
intn,i,c;
int a=-1,b=1;
clrscr();
printf("Enter the number:\n");
scanf("%d",&n); printf("\
nFibonacci Series is :");
for(i=0;i<n;i++)
{ c=a+b;
a=b; b=c;
printf("\n%d",c);
} getch(); }
OUTPUT:
Enter the number: 6
Fibonacci Series is:
0
1
1
2
3
5
RESULT:
Thus the Fibonacci series is generated by using C program has been executed and verified
successfully
9
AIM:
To write a program to find sum of digits
ALGORITHM:
C PROGRAM:
10
/*Sum of Digits*/
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
intn,r,sum=0;
clrscr();
printf("Enter the number:\
n"); scanf("%d",&n);
while(n >0)
{
r=n%10;
sum=sum+r;
n=n/10;
}
printf("\nSum of digits =%d",sum);
getch();
}
OUTPUT :
RESULT:
This sum of digits using C program has been executed and verified successfully.
11
AIM:
To write a program to find sum of Array elements
ALGORITHM:
Step1: Start the program
Step2: Declare an array with necessary size
Step3: Get the value for total number of elements
Step4: Read the inputs
Step5: Initialize the index value and sum value
Step6: Increment the index value by 1
Step7: Repeat the step 4 and 5 until account less than total number of elements
Step8: Printing of all elements of array
Step9: Print the Sum
Step10: Stop the Program
C PROGRAM:
#include<stdio.h>
12
void main()
{
inti,n,a[10],sum=0;
clrscr();
printf("Enter the total no. of elements\n");
scanf("%d", &n);
printf("Enter Array elements one by one\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
sum=sum+a[i];
printf("The sum of Array Elements is %d \n", sum);
getch();
}
OUTPUT:
RESULT: Thus the sum of array elements by using C program has been executed and verified
successfully.
13
AIM:
ALGORITHM:
C PROGRAM:
14
#include<stdio.h>
#include<conio.h
> void main()
{
int a[5][5], b[5][5], c[5][5], r1, r2, c1, c2, i, j, k;
clrscr();
printf("\n Enter the size of matrix A:");
scanf("%d%d", &r1, &c1);
printf("\n Enter the size of matrix B:");
scanf("%d%d", &r2, &c2);
if(c1==r2)
{
printf("\n Enter the elements of matrix A:\n");
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
scanf("%d", &a[i][j]);
printf("\n Enter the elements of matrix B:\n");
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
scanf("%d", &b[i][j]);
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{ c[i]
[j]=0;
for(k=0;k<c1;k++) c[i][j]=c[i][j]+a[i]
[k]*b[k][j];
}}
printf("\n The resultant matrix is:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
printf("%d\t", c[i][j]);
}
printf("\n");
}}
getch();
}
OUTPUT:
Enter the size of matrix A:2
15
2
Enter the size of matrix B:2
2
Enter the elements of matrix A:
9
7
4
5
Enter the elements of matrix B:
6
7
4
6
The resultant matrix is:
82 105
44 58
RESULT:
Thus the multiplication of matrix using C program has been executed and verified successfully.
16
EX.NO:2A) STRING PALINDROME CHECKING
AIM:
To find the string palindrome checking by “C” program
ALGORITHM:
17
C PROGRAM:
#include<stdio.h>
#include<string.h>
void main()
{
char s[20],s1[20];
clrscr();
printf("enter a string \
n"); scanf("%s",s);
strcpy(s1,s);
strrev(s1);
if (strcmp(s,s1)==0)
printf("given string is palindrome \
n"); else
printf("the given string is not palindrome \n");
getch();}
OUTPUT:
Enter a string
DAD
Given string is palindrome
Enter a string
MOM
Given string is not a palindrome
RESULT:
Thus the string palindrome using C program has been executed and verified successfully.
ALGORITHM:
C PROGRAM:
19
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char s[20],s1[20];
clrscr();
printf("Enter the string 1:\n");
scanf("%s",&s);
printf("Enter the string 2:\n");
scanf("%s",&s1);
strcat(s, s1);
printf("The concatenated string is %s\n",s);
getch();
}
OUTPUT:
RESULT:
Thus the string concatenation by using C program has been executed and verified successfully.
20
EX.NO:3A) STUDENT RESULTS CALCULATION USING STRUCTURES
AIM:
ALGORITHM:
C PROGRAM:
21
#include<stdio.h>
#include<conio.h
> struct student
{
introllno;
char name[10];
int m1,m2,m3;
};
void main()
{
struct student s[10];
inttotal,i,n;
floatavg;
clrscr();
printf("Enter the number of students:\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the Student detail:\n");
printf("\nRoll no:\t");
scanf("%d",&s[i].rollno); printf("\
nName:\t"); scanf("%s",s[i].name);
printf("\nFirst subject mark:\t");
scanf("%d",&s[i].m1); printf("\
nSecond subject mark:\t");
scanf("%d",&s[i].m2); printf("\
nThird subject mark:\t");
scanf("%d",&s[i].m3);
total=s[i].m1+s[i].m2+s[i].m3;
avg=(s[i].m1+s[i].m2+s[i].m3)/3; printf("\nTOTAL=%d\
nAVERAGE=%f",total,avg);
if((s[i].m1>=50)&&(s[i].m2>=50)&&(s[i].m3>=50))
{
if(avg>=75)
{
printf("\n DISTINCTION");
}
else if((avg>=60)&&(avg<75))
{
printf("\n FIRST CLASS");
}
else if((avg>=50)&&(avg<60))
{
printf("\n SECOND CLASS");
22
}
}
else
{
printf("\n FAIL");
}
}
getch();
}
OUTPUT:
Enter the number of students:
1
Enter the Student details:
Roll no: 1416103
Name: RAVI
First subject mark: 92
Second subject mark: 93
Third subject mark: 94
Total=279
Average=93.000000
DISTINCTION
RESULT:
Thus the student result calculation using student result calculation using structure in
c program has been executed and verified successfully
ALGORITHM:
24
C PROGRAM:
#include<stdio.h>
#include<conio.h>
union employee
{
intempno;
char name[10];
float BP;
};
void main()
{
union employee E1;
floatHRA,DA,netsalary;
clrscr();
printf("enter the employee details:\
n"); printf("enter the employee
number:"); scanf("%d",&E1.empno);
printf("enter the employee name:");
scanf("%s",&E1.name); printf("\
nenter the basic pay:");
scanf("%f",&E1.BP);
HRA=E1.BP*0.2;
DA=E1.BP*0.5;
netsalary=HRA+DA+E1.BP;
printf("\nHRA=%f\nDA=%f\n Netsalary=%f",HRA,DA,netsalary);
getch();
}
OUTPUT:
25
enter the employee details:
enter the employee number:1416103
enter the employee name:RAVI
enter the basic pay:9000
HRA=1000.000000
DA=4500.000000
Netsalary-15300.000000
RESULT:
Thus the employee net salary calculation using union in C program as been executed and verified
successfully.
26
EX.NO:3C) TO FIND MAXIMUM NUMBER USING POINTER
AIM:
To write a C program to find the maximum number between two numbers using a pointer.
ALGORITHM:
C PROGRAM:
27
#include <stdio.h>
#include
<stdlib.h> void
main()
{
int fno,sno,*ptr1=&fno,*ptr2=&sno;
printf("\n\n Pointer : Find the maximum number between two numbers :\n");
printf(" Input the first number : ");
scanf("%d", ptr1);
printf(" Input the second number : ");
scanf("%d", ptr2);
if (*ptr1>*ptr2)
{
printf("\n\n %d is the maximum number.\n\n",*ptr1);
}
else
{
printf("\n\n %d is the maximum number.\n\n",*ptr2);
}
}
OUTPUT:
RESULT:
Thus the maximum number using pointer in C program has been executed and verified
successfully.
28
EX.NO:3D) REVERSE A STRING USING POINTER
29
AIM:
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the variables str1,revstr,*stptr,*rvptr,i..
STEP 3: Get the string for str1.
STEP 4: Reverse the string
STEP 5: Print the reversed string.
STEP 7: Stop
C PROGRAM:
30
#include <stdio.h>
int main()
{
char str1[50];
char revstr[50];
char *stptr =
str1;
char *rvptr = revstr;
int i=-1;
printf("\n\n Pointer : Print a string in reverse order :\n");
printf(" Input a string : ");
scanf("%s",str1);
while(*stptr)
{
stptr++;
i++;
}
while(i>=0)
{
stptr--;
*rvptr = *stptr;
rvptr++;
--i;
} *rvptr='\0';
printf(" Reverse of the string is : %s\n\n",revstr);
return 0;
}
OUTPUT:
Pointer: Print a string in reverse order:
Input a string: w3resource
Reverse of the string is: ecruoser3w
RESULT:
Thus the C program to print a string in reverse using a pointer has been executed and verified
successfully.
31
EX.NO:4) LARGEST NUMBERS USING DYNAMIC MEMORY ALLOCATION
AIM:
To write a C program to find the largest element using Dynamic Memory Allocation.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the variables I,n,*element
STEP 3: Get the value for total number of elements.
STEP 4: Allocate the memory for all elements
STEP 5: Display the result.
STEP 7: Stop
C PROGRAM:
32
#include <stdio.h>
#include
<stdlib.h> int
main()
{
int i,n;
float *element;
printf("\n\n Pointer : Find the largest element using Dynamic Memory Allocation :\n");
printf(" Input total number of elements(1 to 100): ");
scanf("%d",&n);
element=(float*)calloc(n,sizeof(float)); // Memory is allocated for 'n' elements
if(element==NULL)
{ printf(" No memory is allocated.");
exit(0);
} printf("\n");
for(i=0;i<n;++i) {
printf(" Number %d:
",i+1);
scanf("%f",element+i);
} for(i=1;i<n;++i) {
if(*element<*(element+i))
*element=*(element+i);
} printf(" The Largest element is : %.2f \n\n",*element);
return 0;
}
OUTPUT:
Pointer: Find the largest element using Dynamic Memory Allocation:
Input total number of elements (1 to 100): 5
Number 1: 5
Number 2: 7
Number 3: 2
Number 4: 9
Number 5: 8
The Largest element is: 9.00
RESULT: Thus the C program to find the largest element using Dynamic Memory Allocation
has been executed and verified successfully
33
EX.NO:5A) ARRAY IMPLEMENTATION OF
STACK AIM:
ALGORITHM:
Step 1: Define a stack size.
Step 2: Read the stack operation.
Step 3: Read the stack element.
Step 4: Check the stack operation is Enqueue or Dequeue.
Step 5: If operation is enqueue then check the stack status.
If stack status is over flow we can’t enqueue the element in to stack.
Otherwise we can add the data into stack.
Move top to next position.
PROGRAM:
34
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// A structure to represent a stack
struct Stack
{
int top;
unsigned capacity;
int* array;
};
// function to create a stack of given capacity. It initializes size of
// stack as 0
struct Stack* createStack(unsigned capacity)
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct
Stack)); stack->capacity = capacity;
stack->top = -1;
stack->array = (int*) malloc(stack->capacity * sizeof(int));
return stack;
}
// Stack is full when top is equal to the last index
int isFull(struct Stack* stack)
{ return stack->top == stack->capacity - 1; }
OUTPUT:
10 pushed to
stack 20 pushed
to stack 30
pushed to stack
30 popped from
stack Top item is 20
RESULT:
Thus a C Program using array based implementation of stack was created and executed
successfully.
36
EX.NO:5B) ARRAY IMPLEMENTATION OF
QUEUE AIM:
37
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// A structure to represent a queue
struct Queue
{
int front, rear,
size; unsigned
capacity; int*
array;
};
// function to create a queue of given capacity.
// It initializes size of queue as 0
struct Queue* createQueue(unsigned capacity)
{
struct Queue* queue = (struct Queue*) malloc(sizeof(struct
Queue)); queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1; // This is important, see the
enqueue queue->array = (int*) malloc(queue->capacity *
sizeof(int)); return queue;
}
// Queue is full when size becomes equal to the capacity
int isFull(struct Queue* queue)
{ return (queue->size == queue->capacity); }
// Queue is empty when size is 0
int isEmpty(struct Queue*
queue)
{ return (queue->size == 0); }
39
int rear(struct Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
return queue->array[queue->rear];
}
int main()
{
struct Queue* queue = createQueue(1000);
enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
enqueue(queue, 40);
printf("%d dequeued from queue\n",
dequeue(queue)); printf("Front item is %d\n",
front(queue)); printf("Rear item is %d\n",
rear(queue));
return 0;
}
OUTPUT:
10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
40 enqueued to queue
10 dequeued from
queue Front item is 20
Rear item is 40
RESULT:
Thus the C program for array based implementation of Queue has been executed and verified
successfully
40
6. LINKED LIST IMPLEMENTATION OF STACK AND QUEUE
41
EX.NO:6A) LINKED LIST IMPLEMENTATION OF
STACK AIM:
ALGORITHM:
Step 1: create a list.
i) Create a new empty node top.
ii) Read the stack element and store it in top's data area.
iii) Assign top's link part as NULL (i.e. top->link=NULL).
iv) Assign temp as top (i.e.
temp=top). Step 2: Read next stack operation.
i) If it is Create then go to step1.
ii) If it is push then it process following steps
a) Check Main memory for node creation.
b) Create a new node top.
c) Read the stack element and store it in top's data area.
d) Assign top's link part as temp (i.e. top->link=temp).
e) Assign temp as top (i.e. temp=top).
iii) If it is pop then it process following steps
a) If top is NULL then display stack is empty.
b) Otherwise assign top as temp (i.e. top=temp, bring the top to top position)
c) Assign temp as temp's link. (i.e. temp=temp->link, bring the temp to top's
previous position).
d) Delete top from memory.
iv) If it is traverse then process the following steps
a) Bring the top to stack’s top position(i.e. top=temp)
b) Repeat until top becomes NULL
i) Display the top's data.
ii) Assign top as top's link (top=top->link).
42
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
// A structure to represent a stack
struct StackNode
{
int data;
struct StackNode* next;
};
int main()
{
struct StackNode* root = NULL;
push(&root, 10);
push(&root, 20);
push(&root, 30);
43
printf("%d popped from stack\n", pop(&root));
printf("Top element is %d\n", peek(root));
return 0;
}
OUTPUT:
10 pushed to
stack 20 pushed
to stack 30
pushed to stack
30 popped from
stack Top element is
20
RESULT:
Thus the C program for linked list based implementation of Stack has been executed and verified
successfully.
44
EX.NO:6B) LINKED LIST IMPLEMENTATION OF QUEUE
45
AIM:
To write a C Program using Linked List based implementation of Queue.
ALGORITHM:
Step 1: Initialize the queue variables front =0 and rear = -1
Step 2: Read the queue operation type.
Step 3: Check the queue operations status.
i). If it is Insertion then do the following steps
1. Check rear not equal to null is true increment the rear by one and read the queue
element and also display queue. otherwise display the queue is full.
2. Go to step2.
ii). If it is deletion then do the following steps
1. Check rear< front is true then display the queue is empty.
2. Move the elements to one step forward (i.e. move to previous index ).
3. Decreases the rear value by one (rear=rear-1).
4. Display queue
5. Go to step2.
46
PROGRAM:
#include <stdlib.h>
#include <stdio.h>
struct QNode
{
int key;
struct QNode *next;
};
struct Queue
{
struct QNode *front, *rear;
};
OUTPUT:
Dequeued item is 30
RESULT:
Thus the C program for linked list based implementation of queue has been executed and verified
successfully.
48
EX.NO:7A) CHECKING BALANCED PARENTHESES IN AN EXPRESSION USING
STACK
AIM:
To write a C Program to check balanced parentheses in an expression using stack
ALGORITHM:
Step1: Start
Step 2: Declare a character stack S.
Step 3: Now traverse the expression string exp.
a) If the current character is a starting bracket (‘(‘ or ‘{‘ or ‘[‘) then push it to stack.
b) If the current character is a closing bracket (‘)’ or ‘}’ or ‘]’) then pop from stack and
if the popped character is the matching starting bracket then fine else parenthesis are not
balanced.
Step 4: After complete traversal, if there is some starting bracket left in stack then “not
balanced”
PROGRAM:
49
#include<stdio.h>
#include<stdlib.h
> #define bool int
50
/* If exp[i] is an ending parenthesis then pop from stack and
check if the popped parenthesis is a matching pair*/
if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
{
/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
char exp[100] = "{()}[]";
if (areParenthesisBalanced(exp))
printf("Balanced \n");
else
printf("Not Balanced \n");
return 0;
}
void push(struct sNode** top_ref, int new_data)
{
struct sNode* new_node = (struct sNode*) malloc(sizeof(struct sNode));
if (new_node == NULL)
{
printf("Stack overflow
n"); getchar();
exit(0);
}
51
new_node->data = new_data;
new_node->next =
(*top_ref); (*top_ref) =
new_node;
}
int pop(struct sNode** top_ref)
{
char res;
struct sNode *top;
if (*top_ref == NULL)
{
printf("Stack overflow
n"); getchar();
exit(0);
}
else
{
top = *top_ref;
res = top-
>data;
*top_ref = top->next;
free(top);
return res;
}
}
OUTPUT:
Balanced
RESULT:
Thus the C program for checking balanced parentheses in an expression using stack has been
executed and verified successfully.
52
EX.NO:7B) INFIX TO POSTFIX CONVERSION USING STACK
53
AIM:
To write a ‘C’ program to implement stack and use it to convert infix to postfix expression.
ALGORITHM:
1. Start the program
2. Scan the Infix string from left to right.
3. Initialise an empty stack.
4. If the scannned character is an operand, add it to the Postfix string. If the scanned
character is an operator and if the stack is empty Push the character to stack.
If the scanned character is an Operand and the stack is not empty,
compare the precedence of the character with the element on top of the
stack (topStack). If topStack has higher precedence over the scanned
character Pop the stack else Push the scanned character to stack. Repeat
this step as long as stack is not empty and topStack has precedence over
the character.
Repeat this step till all the characters are scanned.
5. (After all characters are scanned, we have to add any character that the stack may have
to the Postfix string.) If stack is not empty add topStack to Postfix string and Pop the
stack. Repeat this step as long as stack is not empty.
6. Return the Postfix string.
7. Terminate the program.
PROGRAM:
54
#include<stdio.h>
#include<string.h>
#define size 10
char stack[size];
int tos=0,ele;
void push();
char pop();
void show();
int isempty();
int isfull();
char infix[30],output[30];
int prec(char);
int main()
{
int i=0,j=0,k=0,length;
char temp;
printf("\nEnter an infix expression:");
scanf("%s",infix);
printf("\nThe infix expresson is %s",infix);
length=strlen(infix);
for(i=0;i<length;i++)
{
//Numbers are added to the out put QUE
if(infix[i]!='+' && infix[i]!='-' && infix[i]!='*' && infix[i]!='/' && infix[i]!='^' &&
infix[i]!=')' && infix[i]!='(' )
{
output[j++]=infix[i];
printf("\nThe element added to Q is:%c",infix[i]);
} else
{ if(tos==0) //If there are no elements in the stack, the operator is added to it
{
push(infix[i]);
printf("\nThe pushed element is:%c",infix[i]);
} else
{ //Operators or pushed or poped based on the order of
precedence if(infix[i]!=')' && infix[i]!='(')
{ if( prec(infix[i]) <= prec(stack[tos-1]) )
{
temp=pop();
printf("\n the poped element is :%c",temp);
output[j++]=temp;
push(infix[i]);
printf("\n The pushed element is :%c",infix[i]);
show();
}
else
{
push(infix[i]);
printf("\nThe pushed element is:%c",infix[i]);
show();
}
}
else
55
{
if(infix[i]=='(')
{
push(infix[i]);
printf("\nThe pushed-- element is:%c",infix[i]);
}
if(infix[i]==')')
{
temp=pop();
while(temp!='(')
{output[j++]=temp;
printf("\nThe element added to Q is:%c",temp);
//temp=pop();
printf("\n the poped element is :%c",temp);
temp=pop();}
}}}}
printf("\nthe infix expression is: %s",output);
}
while(tos!=0)
{
output[j++]=pop();
}
printf("the infix expression is: %s\n",output);
}void push(int ele)
{ stack[tos]=ele;
tos++;
}
char pop()
{
tos--;
return(stack[tos]);
}
void show()
{
int x=tos;
printf("--The Stack elements are....");
while(x!=0)
printf("%c, ",stack[--x]);
}
//Function to get the precedence of an operator
int prec(char symbol)
{
if(symbol== '(')
return 0;
if(symbol== ')')
return 0;
if(symbol=='+' || symbol=='-')
return 1;
if(symbol=='*' || symbol=='/')
return 2;
if(symbol=='^')
return 3;
return 0;
56
}
Output:
RESULT:
Thus the C program for infix to postfix conversion has been executed successfully.
57
EX.NO:8A) IMPLEMENTATION OF TREE
AIM:
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the structure for node
STEP 3: Declare all variables
STEP 4: Recursively create new nodes
STEP 5: Display the order of nodes
STEP 7: Stop
C PROGRAM:
58
#include <stdio.h>
#include
<stdlib.h> struct
node {
int data;
struct node* left;
struct node*
right;
};
struct node* createNode(value){
struct node* newNode = malloc(sizeof(struct
node)); newNode->data = value;
newNode->left = NULL;
newNode->right =
NULL; return
newNode; }
struct node* insertLeft(struct node *root, int value)
{ root->left = createNode(value);
return root->left; }
struct node* insertRight(struct node *root, int value)
{ root->right = createNode(value);
return root->right; }
int main(){
struct node *root = createNode(1);
insertLeft(root, 2);
insertRight(root, 3);
printf("The elements of tree are %d %d %d", root->data, root->left->data, root->right->data);
}
OUTPUT:
123
RESULT:
Thus the C program for implementation of tree has been executed successfully.
59
EX.NO:8B) IMPLEMENTATION OF TREE TRAVERSAL
AIM:
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the structure for node
STEP 3: Declare all variables
STEP 4: Recursively apply pre-order, post-order and in-order
STEP 5: Display the nodes
STEP 7: Stop
60
C PROGRAM:
#include <stdio.h>
#include
<stdlib.h> struct
node
{
int data;
struct node* left;
struct node*
right;
};
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct
node)); node->data = data;
node->left = NULL;
node->right =
NULL; return(node);
}
void printPostorder(struct node* node)
{
if (node ==
NULL) return;
// first recur on left
subtree
printPostorder(node->left);
// then recur on right
subtree printPostorder(node-
>right);
// now deal with the node
printf("%d ", node->data);
}
61
/* first print data of node */
printf("%d ", node->data);
62
/* then recur on left sutree
*/ printPreorder(node->left);
OUTPUT:
Preorder traversal of binary tree is
12453
Inorder traversal of binary tree is
42513
Postorder traversal of binary tree is
45231
RESULT:
Thus the C program for implementation of tree traversal has been executed successfully.
63
EX.NO:9) IMPLEMENTATION OF BINARY SEARCH TREE
AIM:
To write a C program to perform Insert, Delete, Search an element into a binary search tree.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the structure for node
STEP 3: Declare all variables
STEP 4: Recursively apply pre-order, post-order and in-order
STEP 5: Display the nodes
STEP 7: Stop
C PROGRAM:
64
#include<stdio.h>
#include<stdlib.h
> struct node
{
int data;
struct node* left;
struct node*
right;
};
struct node* createNode(value){
struct node* newNode = malloc(sizeof(struct
node)); newNode->data = value;
newNode->left = NULL;
newNode->right =
NULL;
return newNode;
}
struct node* insert(struct node* root, int data)
{
if (root == NULL) return createNode(data);
66
OUTPUT:
RESULT:
Thus the C program for implementation of binary search tree has been executed
successfully.
67
EX.NO:10A) IMPLEMENTATION OF LINEAR SEARCH
AIM:
ALGORITHM:
Step 1 Initialization Set i =1.
Step 2 Loop, Comparison
while ( i < = N)
{
if (k = ki) then
{
message : ‗‗successful search‘‘
display (k) go to step 4
}
else
Set i =i + 1
}
End of
loop.
Step 3 If no match
If (k = ki) then
message : "unsuccessful search".
Step 4 Finish Exit.
68
C PROGRAM:
69
#include<stdio.h>
#include<conio.h
> void main()
{
int a[10],i,n,m,c=0;
clrscr();
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array:
"); for(i=0;i<=n-1;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the number to be search: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++)
{
if(a[i]==m)
{
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
else
printf("The number is found");
getch();
}
Output:
70
RESULT:
AIM:
71
To Write a C program to perform Binary Search in one dimensional array.
ALGORITHM:
Step 1 Initialization. Set l = 1, u = N.
Step 2 Middle key, loop.
while (u > = l)
{
Set m=1.
if (K = km) then
{
Message : "successful
search". display (K).
}
else if (K > km)
Set l =m + 1.
else
Set u = m – 1.
}
End of loop.
Step 3 Return at the point of call.Return.
C PROGRAM:
72
#include<stdio.h>
#include<conio.h
> void main(){
int a[10],i,n,m,c=0,l,u,mid;
clrscr();
l=0,u=n-1;
while(l<=u){
mid=(l+u)/2;
if(m==a[mid]){
c=1;
break;
}
else if(m<a[mid]){
u=mid-1;
}
else
l=mid+1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
getch();
}
OUTPUT:
73
RESULT:
74
EX.NO:11A) BUBBLE SORT
AIM:
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the variables of respective datatype.
list[20],num,min,temp,i,j;=>int.
Step 3: Enter the number of elements(max.20).
Step 4: Read the value of num.
Step 5: Display enter the elements.
Step 6: for(i=0;i<num;i++) read the value of list[i].
Step 7:for(i=0;i<num-1;i++)then for(j=0;j<num-1-i;j++).if(list[j]>list[j+1]).
Step 8:do temp=list[j]. list[j]=list[j+1]. List[j+1]=temp.
Step 9:Display “after sorting elements are” for(i=0;i<num;i++)
Step 10:Display the elements present in the list[i].
75
PROGRAM:
#include<stdio.h>
#include<conio.h
> void main()
{
int list[20],num,min,temp,i,j;
clrscr();
printf("\n enter the number of elements(max.20) \t");
scanf("%d",&num);
printf("\n enter the
elements:"); for(i=0;i<num;i+
+) scanf("%d",&list[i]);
for(i=0;i<num-1;i++)
for(j=0;j<num-1-i;j++)
if(list[j]>list[j+1])
{
temp=list[j];
list[j]=list[j+1];
list[j+1]=temp;
}
printf("\n after sorting elements are:");
for(i=0;i<num;i++)
printf("%d \n",list[i]);
getch();
}
OUTPUT:
76
RESULT:
Thus a C program to perform the bubble sort for the given numbers is executed and verified
successfully.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the structure for node
STEP 3: Declare all variables
STEP 4: Recursively apply pre-order, post-order and in-order
STEP 5: Display the nodes
STEP 7: Stop
78
PROGRAM:
#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
printf("Enter number of elements\n");
scanf("%d", &n);
printf("Enter %d integers\n", n);
for (c = 0; c < n; c++) {
scanf("%d", &array[c]);
}
OUTPUT:
79
RESULT:
Thus a C program to perform the insertion sort for the given numbers is executed and verified
successfully.
ALGORITHM:
1. If n < = 1, then return.
2. Pick any element V in a[]. This is called the pivot.
3. Rearrange elements of the array by moving all elements xi > V right of V and all
elements xi < = V left of V. If the place of the V after re-arrangement is j, all elements with
value less than V, appear in a[0], a[1]........a[j – 1] and all those with value greater than V
appear in a[j + 1]........a[n – 1].
4. Apply quick sort recursively to a[0] . . . . a[j – 1] and to a[j + 1]........a[n – 1].
PROGRAM:
81
#include <stdio.h>
void quick_sort(int[],int,int);
int partition(int[],int,int);
int main()
{
int a[50],n,i;
printf("How many elements?");
scanf("%d",&n);
printf("\nEnter array
elements:"); for(i=0;i<n;i++)
scanf("%d",&a[i]);
quick_sort(a,0,n-1); printf("\
nArray after sorting:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}
do
{
do
i++;
while(a[i]<v&&i<=u);
do
j--;
while(v<a[j]);
if(i<j)
{
temp=a[i];
a[i]=a[j];
74
a[j]=temp;
}
}while(i<j);
a[l]=a[j];
a[j]=v;
return(j);
}
OUTPUT:
RESULT:
Thus a C program to perform the quick sort for the given numbers is executed and verified
successfully.
75
AIM:
ALGORITHM:
1. If n < = 1, then return.
2. Pick any element V in a[]. This is called the pivot.
3. Rearrange elements of the array by moving all elements xi > V right of V and all
elements xi < = V left of V. If the place of the V after re-arrangement is j, all elements with
value less than V, appear in a[0], a[1]........a[j – 1] and all those with value greater than V
appear in a[j + 1]........a[n – 1].
4. Apply quick sort recursively to a[0] . . . . a[j – 1] and to a[j + 1]........a[n – 1].
76
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define MAX_SIZE 5
void merge_sort(int, int);
void merge_array(int, int, int, int);
int arr_sort[MAX_SIZE];
int main() {
int i;
printf("Simple Merge Sort Example - Functions and Array\n");
printf("\nEnter %d Elements for Sorting\n", MAX_SIZE);
for (i = 0; i < MAX_SIZE; i++)
scanf("%d", &arr_sort[i]);
if (i < j) {
m = (i + j) / 2;
merge_sort(i, m);
merge_sort(m + 1,
j);
// Merging two arrays
merge_array(i, m, m + 1, j);
}
}
OUTPUT:
Your Data : 67 57 45 32 13
Sorted Data : 13 32 45 57 67
RESULT:
Thus a C program to perform the merge sort for the given numbers is executed and verified
successfully.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the structure for node
STEP 3: Declare all variables
STEP 4: Recursively apply pre-order, post-order and in-order
STEP 5: Display the nodes
STEP 7: Stop
79
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 10
void main()
{
int a[MAX],num,key,i;
char ans;
int create(int);
void linear_prob(int [],int,int),display(int []);
clrscr();
printf("\n Collision Handling By Linear Probing");
for(i=0;i<MAX;i++)
a[i]=-1;
do
{
printf("\n Enter the Number ");
scanf("%d",&num);
key=create(num);
linear_prob(a,key,num);
printf("\n Do U Wish to Contiue?(Y/N");
ans=getch();
}
while(ans=='y');
display(a);
getch();
}
int create(int num)
{
int key;
key=num%10;
return key;
}
void linear_prob(int a[MAX],int key,int num)
{
int flag,i,count=0;
void display(int a[]);
flag=0;
if(a[key]==-1)
a[key]=num;
else
{ i=
0;
while(i<MAX)
80
{
if(a[i]!=-1)
count++;
i++;
}
if(count==MAX)
{ printf("\n\n Hash Table is Fu;;");
display(a);
getch();
exit(1);
}
for(i=key+1;i<MAX;i+
+) if(a[i]==-1)
{ a[i]=num;
flag=1;
break;
}
for(i=0;i<key&&flag==0;i++)
if(a[i]==-1)
{
a[i]=num;
flag=1;
break;
}}}
void display(int a[MAX])
{ int i;
printf("\n\n The HAsh Table is....\n");
for(i=0;i<MAX;i++)
printf("\n %d %d",i,a[i]);
}
OUTPUT:
81
RESULT: Thus the program has been executed successfully.
82
Ex. No. 13) Implementation of AVL tree
Aim:
To Implement Insertion in AVL Trees
Algorithm:
Step 1: Create a class AVL tree and declare all its member variables and functions
Step 2: Get the user option if tge choice is 1, create a binary tree, with the values and
considering the Balance factor
Step 3:The balance factor=no of left child-no of right child
Step4:If the balance factor is not equal to 1, 0,-1 then we have to rotate the tree one time left or
right or Double rotate
Step5:If the option is 2, display the tree contents in preorder and postorder formats
Step 6:If the option is 3, get the element to be searched and display whether the element is
present or Not.
Step 7: If the option is 4, exit the program
Program:
#include<conio.h>
#include<stdio.h>
83
node *RL(node *);
}while(op!=5);
84
}
node * insert(node *T,int x)
{
if(T==NULL)
{
T=(node*)malloc(sizeof(node));
T->data=x;
T->left=NULL;
T->right=NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=insert(T->right,x);
if(BF(T)==-2)
if(x>T->right->data)
T=RR(T);
else
T=RL(T);
}
else
if(x<T->data)
{
T->left=insert(T->left,x);
if(BF(T)==2)
if(x < T->left->data)
T=LL(T);
else
T=LR(T);
}
T->ht=height(T);
return(T);
}
if(T==NULL)
{
return NULL;
}
else
T->data=p->data;
T->right=Delete(T->right,p->data);
if(BF(T)==2)//Rebalance during
windup if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}
88
return(T);
}
node * RL(node *T)
{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}
int BF(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
return(lh-rh);
}
void preorder(node *T)
{
if(T!=NULL)
{
printf(" %d(Bf=%d)",T-
>data,BF(T)); preorder(T->left);
preorder(T->right);
}
}
void inorder(node *T)
{
if(T!=NULL)
{
inorder(T->left);
printf(" %d(Bf=%d)",T-
>data,BF(T)); inorder(T->right);
}
}
OUTPUT:
89
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Preorder sequence:
7(Bf=-1)4(Bf=0)12(Bf=1)9(Bf=0)
Inorder sequence:
4(Bf=0)7(Bf=-1)9(Bf=0)12(Bf=1)
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Enter a data:7
1)Create:
2)Insert:
3)Delete:
4)Print:
5)Quit:
Preorder sequence:
9(Bf=0)4(Bf=0)12(Bf=0)
Inorder sequence:
4(Bf=0)9(Bf=0)12(Bf=0)
90
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
RESULT:
Thus the C program To Implement Insertion in AVL Trees was written and verified.
91
Ex. No. 14 IMPLEMENTATION OF MINIMUM SPANNING TREE USING
PRIM’S ALGORITHM
Aim:
To Implement Prim’s algorithm using priority queues to find MST of an undirected graph
Algorithm:
Step 1: Create the class prim with all its member variables and member functions.
Step 3: Get the cost for every edges between the vertices of the graph
Step 4: Assign the lowest cost edges, to form a path from the first nodes to the last vertex
Of the graph
Step 5: Display the minimum cost spanning tree for the graph with the path
92
Program:
/*prims alg prg*/
#include<iostream.h>
#include<conio.h>
#include<process.h>
float lcost[100],a[100][100];
int closest[100],i,j,k,min,n;
int v1,v2,wt,c=0;
class prim
public:
void get_mat()
cin>>n;
cout<<"enter weighted
matrix"<<endl; for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cin>>a[i][j];
}//inner for
}//outer for
}//fn
void prim1()
93
for(i=2;i<=n;i++)
lcost[i]=a[1][i];
closest[i]=1;
for(i=2;i<=n;i++)
min=lcost[2];
k=2;
for(j=3;j<=n;j++)
if(lcost[j]<min)
min=lcost[j];
k=j;
c=c+min; cout<<"("<<closest[k]<<","<<k<<")"<<"\
t"<<"cost="<<min<<"\t"; lcost[k]=2000;
for(j=2;j<=n;j++) if((a[k]
[j]<lcost[j])&&(lcost[j]<2000))
lcost[j]=a[k][j];
closest[j]=k;
cout<<"\n";
94
}//outer for
getch();
};
void main()
clrscr();
int ch;
prim p;
do
cin>>ch;
switch(ch)
case 1:
p.get_mat();
break;
case 2:
p.prim1();
break;
case 3:
exit(0);
break;
}//switch
}while(ch<=3);//do
getch();
95
}//main
OUTPUT:
1. Insert
3. Exit
96
Enter the cost between the edge 4,4:1000
Enter your
(1,1) cost=1
(1,3) cost=2
(1,4) cost=2
(4,5) cost=4
RESULT:
Thus the C program To Implement Prim’s algorithm using priority queues to find MST of
an undirected graph was written and executed successfully.
97