Sei sulla pagina 1di 164

1.

1 LINEAR SEARCH
AIM
To implement linear search using C program.
ALGORITHM
Start
1 .i=1
2. if(k=A[i]) then
3. print „Successful‟at location i
4. Go to step 14
5. else
6. i=i+1
7. If(i<=n) then
8. Go to step 2
9. else
10. printf „Unsuccessful‟
11. Go to step 14
12. end if
13. end if
Stop
SOURCE CODE
// 1.1 LINEAR SEARCH //
#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,a[20],x,flag=0;
clrscr();
printf("LINEAR SEARCH");
//GET THE INPUT
printf("\n\nEnter the number of elements\n");
scanf("%d",&n);
printf("\nEnter the array elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the element to be searched\n");
scanf("%d",&x);
// PERFORMS SEARCHING
for(i=0;i<n;i++)
{
if(x==a[i])
{
// PRINTS THE FOUND ELEMENT & ITS POSITION
printf("\nThe given element %d is found in position %d\n", x,i+1);
flag=1;
break;
}
}
// PRINTS IF THE ELEMENT IS NOT FOUND
if(flag==0)
{
printf("\nElement not found\n");
}
getch();
}
OUTPUT
RESULT
Thus linear search has been implemented using C program.
1.2 BINARY SEARCH
AIM
To implement binary search using C program.
ALGORITHM
Start
1.L=1,u=n
2.flag=False
3. While(flag!=True) and (l<u) do
4. mid=(l+u)/2
5. if(k=A[mid]) then
6. print „Successful‟
7. flag=TRUE
8. Return(mid)
9. end if
10. if(k<A[mid]) then
11. U=mid-1
12. else
13. l=mid+1
14. end if
15. end while
16. if(flag=FALSE) then
17. print “unsuccessful‟
18. return -1
19. end if
Stop
SOURCE CODE
//1.2 BINARY SEARCH //
//HEADER FILES
#include<stdio.h>
#include<conio.h>
//DECLARATION
int i,mid,low,high,n,x,a[20],index;
int binsearch();
void main()
{
clrscr();
// GETS THE INPUT
printf("\nEnter the number of elements :\n");
scanf("%d",&n);
printf("\nEnter the array elements in sorted order:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter the element to search:\n");
scanf("%d",&x);
index=binsearch();
if(index!=-1)
{
printf("\nElement %d is found in position %d\n",x,index+1);
}
else
{
printf("\nElement not found\n");
}
getch();
}
// PERFORMS BINARY SEARCH
int binsearch()
{
low=0;
high=n-1;
while (low<high)
{
mid=(low+high)/2;
if(x==a[mid])
{
return mid;
}
else if(x>a[mid])
{
low=mid+1;
}
else if(x<a[mid])
{
high=mid-1;
}
}
return -1;
}
OUTPUT
RESULT
Thus binary search has been implemented using C program.
2.3 BUBBLE SORT
AIM
To implement bubble sort using C program.
ALGORITHM
For i=1 to n-1
For j=1 to n-i
If(a[j]>a(j+1)
Swap(a[j],a[j+1])
End if
End for
End for
SOURCE CODE
// 2.3 BUBBLE SORT
#include<stdio.h>
#include<conio.h>
int a[20],k,i,n,temp,j;
void get(); // TO GET INPUT
void sort(); // TO PERFORM SORTING
void display(int[],int); // TO DISPLAY SORTED ELEMENTS
void main()
{
clrscr();
printf("\n\t\tBUBBLE SORT\n");
get();
sort();
getch();
}
// GETS THE NUMBER OF ELEMENTS AND DISPLAYS IT IN
UNSORTED ORDER
void get()
{
printf("\nEnter the number of elements:\n");
scanf("%d",&n);
printf("\nThe elements are:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
printf("\nThe unsorted elements are:\n");
display(a,n);
}
// PERFORMS SORTING OPERATION
void sort()
{
for(j=1;j<=n;j++)
{
for(k=1;k<=n-j;k++)
{
if(a[k]>a[k+1])
{
temp=a[k];
a[k]=a[k+1];
a[k+1]=temp;
}
}
printf("\nPASS: %d",j);
display(a,n);
}
printf("\n\nSorted elements are:\n");
display(a,n);
}
//DISPLAYS THE OUTPUT
void display(int a[], int n)
{
for(i=1;i<=n;i++)
{
printf("\t%d",a[i]);
}
}
OUTPUT
RESULT
Thus bubble sort has been implemented using C program.
2.8 QUICK SORT
AIM
To implement quick sort using C program.
ALGORITHM
Quick sort(A,first,last)
1. If(first<last) then
2. P=Partition(A,first,last)
3. Quick sort(A,first,P-1)
4. Quick sort(A,P+1,last)
5. Return
SOURCE CODE
/* 2.8 QUICK SORT */
#include<stdio.h>
#include<conio.h>
int a[10],i,j,n,temp,pivot;
void qsort();
void interchange();
int partition();
void display();
void main()
{
clrscr();
printf("\n QUICK SORT \n");
printf("\nEnter the number of elements:\n");
scanf("%d",&n);
printf("\nEnter the numbers:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
qsort(0,n-1);
display();
getch();
}
void qsort(int left,int right)
{
if(left<right)
{
j=partition(a,left,right);
qsort(left,j-1);
qsort(j+1,right);
}
}
int partition(int a[],int left,int right)
{
if(left<right)
{
pivot=a[left];
i=left;
j=right+1;
do
{
// Find bigger than pivot value from left to right
do
{
i++;
}while(a[i]<pivot);
// Find smaller than pivot value from right to left
do
{
j--;
}while(a[j]>pivot);
if(i<j)
{
interchange(a,i,j);
}
}while(i<j);
// Insert pivot as partition element
interchange(a,left,j);
}
return j;
}
void interchange(int a[],int i,int j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
void display()
{
printf("\nSorted elements are:\n");
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
}
OUTPUT
RESULT
Thus quick sort has been implemented using C program.
2.7 MERGE SORT
AIM
To implement merge sort using C program.
ALGORITHM
Void merge sort(int a[], int temp[], int n)
{
Msort(A, temp, 0, n-1);
}
Void msort(int a[], int temp[]. Int left, int right)
{
Int center;
If(left<right)
{
Center=(right+left)/2;
Msort(A, temp, left, right);
Msort(A, temp,center+1, right);
Merge(A, temp, left, center+1, right);
}
}
SOURCE CODE
/* 2.7 MERGE SORT */
#include<stdio.h>
#include<conio.h>
int i,n,a[10];
void partition();
void msort();
void display();
void main()
{
clrscr();
printf("\n\t\t MERGE SORT\n");
printf("\nEnter the number of elements:\n");
scanf("%d",&n);
printf("\nEnter the values \n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
partition(1,n);
display(n);
getch();
}
//partition upto 1 or 2 elements
void partition(int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
partition(low,mid);
partition(mid+1,high);
msort(low,mid,high);
}
}
// Performs sorting and merging
void msort(int low,int mid,int high)
{
int b[10];
int i,j,m,k;
m=low;
i=low;
j=mid+1;
// compare two partition
while(i<=mid && j<=high)
{
if(a[i]<a[j])
{
b[m]=a[i];
i=i+1;
}
else
{
b[m]=a[j];
j=j+1;
}
m=m+1;
}
//append remaining element
if(i<=mid)
{
for(k=i;k<=mid;k++)
{
b[m]=a[k];
m=m+1;
}
}
else if(j<=high)
{
for(k=j;k<=high;k++)
{
b[m]=a[k];
m=m+1;
}
}
// copy to a[]
for(k=low;k<=high;k++)
{
a[k]=b[k];
}
}
void display(int n)
{
int i;
printf("\nThe sorted array is:\n");
for(i=1;i<=n;i++)
{
printf("\t%d",a[i]);
}
}
OUTPUT
RESULT
Thus merge sort has been implemented using C program.
2.2 SELECTION SORT
AIM
To implement selection sort using C program.
ALGORITHM
Straight selection sort:
For i=n to (n-1) do
J=selection min(i,n)
If(i!=j) then
Swap(A[i],A[j])
End if
End for
Stop
Selection Minimum:
Min=A[L]
Min loc=L
For i=L+i to R do
If (min>A[i]) then
Min=A[i]
Min loc=i
End if
End for
Return(min loc)
SOURCE CODE
//2.2 SELECTION SORT
#include<stdio.h>
#include<conio.h>
int i,j,t,n,k,a[20],min;
void get(); // TO GET INPUT
void sort(); // TO PERFORM SORTING
void display(int[],int);
void main()
{
clrscr();
printf("\n\t\t SELECTION SORT");
get();
sort();
getch();
}
// GETS THE NUMBER OF ELEMENTS AND DISPLAYS IT IN
UNSORTED ORDER
void get()
{
printf("\nEnter the number of elements:\n");
scanf("%d",&n);
printf("\nEnter the elements:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
printf("\nThe unsorted elements are:\n");
display(a,n);
}
// PERFORMS SORTING OPERATION
void sort()
{
for(k=1;k<n;k++)
{
min=k;
for(j=k+1;j<=n;j++)
{
if(a[j]<a[min])
{
min=j;
}
}
if(min!=k)
{
t=a[k];
a[k]=a[min];
a[min]=t;
}
printf("\n PASS: %d",k);
display(a,n);
}
printf("\nSorted Elements are:\n");
display(a,n);
}
//DISPLAYS THE OUTPUT
void display(int a[], int n)
{
for(i=1;i<=n;i++)
{
printf("\t%d",a[i]);
}
}
OUTPUT
RESULT
Thus selection sort has been implemented using C program.
2.1 INSERTION SORT
AIM
To implement insertion sort using C program.
ALGORITHM
Void insertion_sort(int a[],int n)
{
IntI,j,temp;
For(i=0;i<n;i++)
{
Temp=a[i];
For (j=1;j<0&&a[j-1]>temp;j--)
{
A[j]=a[j-1];
}
A[j]=temp;
}
}
SOURCE CODE
//2.1 INSERTION SORT
#include<stdio.h>
#include<conio.h>
int a[20],i,j,k,n,key;
void get(); // TO GET INPUT
void sort(); // TO PERFORM SORTING
void display(int[],int);
void main()
{
clrscr();
printf("\n\t\tINSERTION SORT\n");
get();
sort();
getch();
}
// GETS THE NUMBER OF ELEMENTS AND DISPLAYS IT IN
UNSORTED ORDER
void get()
{
printf("\nEnter the number of elements:\n");
scanf("%d",&n);
printf("\nThe array elements are:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
printf("\nThe unsorted elements are:\n");
display(a,n);
}
// PERFORMS SORTING OPERATION
void sort()
{
for(j=2;j<=n;j++)
{
key=a[j];
i=j-1;
while((i>0) && (key < a[i]))
{
a[i+1]=a[i];
i=i-1;
}
a[i+1]=key;
printf("\nPass %d :", j-1);
display(a,n);
}
printf("\n\nSorted elements are:\n");
display(a,n);
}
//DISPLAYS THE OUTPUT
void display(int a[], int n)
{
for(i=1;i<=n;i++)
{
printf("\t%d",a[i]);
}
}
OUTPUT
RESULT
Thus insertion sort has been implemented using C program.
2.4 SHELL SORT
AIM
To implement shell sort using C program.
ALGORITHM
Void shell sort(int A[], int N)
{
IntI,j,k,temp;
For(k=N/2;k>0;k=k/2)
For(i=k;i<N;i++)
{
Temp=A[i];
For(j=1;j>=k && A[j=k]>temp;j=j-k)
{
A[j]=A[j-k];
}
A[j]=temp;
}
}
SOURCE CODE
// 2.4 SHELL SORT
#include<stdio.h>
#include<conio.h>
int n,i,t,dist,a[20],swap;
void get(); // TO GET INPUT
void shellsort(); // TO PERFORM SORTING
void display(int[],int);// TO DISPLAY THE OUTPUT
void main()
{
clrscr();
printf("\n\t\tSHELL SORT\n");
get();
shellsort();
getch();
}
// GETS THE NUMBER OF ELEMENTS AND DISPLAYS IT IN
UNSORTED ORDER
void get()
{
printf("\nEnter the number of elements:");
scanf("%d",&n);
printf("\nEnter the elements:\n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
printf("\n\nThe unsorted elements are:\n");
display(a,n);
}
// PERFORMS SORTING OPERATION
void shellsort()
{
dist=n/2;
do
{
do
{
swap=0;
for(i=1;i<=n-dist;i++)
{
if(a[i]>a[i+dist])
{
t=a[i];
a[i]=a[i+dist];
a[i+dist]=t;
swap=1;
}
}
printf("\nDistance %d:", dist);
display(a,n);
}while(swap);
dist=dist/2;
}while(dist);
printf("\n\nSorted Elements are", dist);
display(a,n);
}
//DISPLAYS THE OUTPUT
void display(int a[], int n)
{
for(i=1;i<=n;i++)
{
printf("\t%d",a[i]);
}
}
OUTPUT
RESULT
Thus shell sort has been implemented using C program.
2.6 RADIX SORT
AIM
To implement radix sort using C program.
ALGORITHM
Start
For i=1 to c do
For j=1 to n do
X=Entract(A[j],i)
Enque(Qx,A[j])
End for
For k=0 to b-1 do
While Qx is not empty do
Y=Dequeue(Qx)
Insert(A,y)
End while
End for
End for
Stop
SOURCE CODE
/* 2.6 RADIX SORT */
#include<stdio.h>
#include<conio.h>
int a[15],n,r,i,divisor,digit=0,j,k,max,p,tc,sc;
int bucket[10][10],bc[10];
void get();
void rsort();
void display(int[],int);
void main()
{
clrscr();
printf("\n\t\tRADIX SORT");
get();
rsort();
getch();
}
void get()
{
printf("\nEnter the number of elements:\n");
scanf("%d",&n);
printf("\nEnter the array elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nThe unsorted elements are:\n");
display(a,n);
}
void rsort()
{
// TO FIND THE MAXIMUM ELEMENT
max=a[0];
for(i=0;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
// TO IDENTIFY THE MAXIMUM NUMBER OF DIGITS IN THE
GIVEN INPUT
while(max>0)
{
digit++;
max=max/10;
}
// TO SORT THE ELEMENTS USING MODULO DIVISION
divisor=1;
for(p=0;p<digit;p++)
{
for(i=0;i<10;i++)
{
bc[i]=0;
}
for(i=0;i<n;i++)
{
r=(a[i]/divisor)%10;
bucket[r][bc[r]]=a[i];
bc[r]++;
}
i=0;
for(k=0;k<10;k++)
{
for(j=0;j<bc[k];j++)
{
a[i++]=bucket[k][j];
}
}
divisor=divisor*10;
}
printf("\nSorted elements are:\n");
display(a,n);
}
//TO PRINT THE ELEMENTS IN SORTED ORDER
void display(int a[], int n)
{
for(i=0;i<n;i++)
{
printf("\t%d",a[i]);
}
}
OUTPUT
RESULT
Thus radix sort has been implemented using C program.
2.5 HEAP SORT
AIM
To implement heap sort using C program.
ALGORITHM
Create heap:
Start
1. i=1
2. while(i<=n) do
3. x=A[i]
4. B[i]=x
5. j=1
6. while(j>1) do
7. if(B[j]>B[j/2)
8. temp=B[j]
9. B[j]=B[j/2]
10. B[j/2]=temp
11. j=j/2
12. else
13. j=1
14. end if
15. end while
16. i=i+1
17. end while
Stop
Remove max:
1. temp=B[j]
2. B[i]=B[1]
3. B[1]=B[i]
4. Stop
Rebuild heap:
1.If(i=1) then
2. exit
3.j=1
4.Flag=True
5.while(Flag=TRUE) do
6. leftchild=2*j
7.if(rightchild<=i) then
8. if(B[j]<=B[leftchild] and B[left child]>= B[rightchild] then
9.swap(B[j],B[left child]
10.j=leftchild
11.else
12.if[B[j]<=B[rightchild] and B[rightchild]>=B[leftchild] then
13.swap(B[j],B[rightchild]
14.j=right child
15.else
16.Flag=False
17.End if
18.End if
19.else
20.if(leftchild<=i) then
21.if(B[j]<=B[leftchild] then
22.swap(B[j],B[leftchild])
23.j=leftchild
24.else
25.Flag=False
26.End if
27.End if
28.End if
29.End while
30.Stop
SOURCE CODE
/* 2.5 HEAPSORT */
#include<stdio.h>
#include<conio.h>
int a[20],n,i,j,key,t;
void getdata(); // TO GET INPUT
void heapify(int[],int);// TO CREATE HEAP
void hsort(int[],int); // TO PERFORM SORTING
void adjust(int[],int,int); // TO ADJUST TO HEAP STRUCTURE
void display(int[],int); // TO DISPLAY OUTPUT
void main()
{
clrscr();
printf("\n\t\tHEAP SORT");
getdata();
getch();
}
// GETS THE NUMBER OF ELEMENTS IN UNSORTED ORDER
void getdata()
{
printf("\nEnter the number of elements\n");
scanf("%d", &n);
printf("\nEnter the elements to be sorted\n");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
hsort(a,n);
printf("\nSorted elements are:\n");
display(a,n);
}
// PERFORMS SORTING OPERATION
void hsort(int a[],int n)
{
heapify(a,n);
for(i=n;i>=2;i--)
{
t=a[i];
a[i]=a[1];
a[1]=t;
adjust(a,1,i-1);
}
}
// CREATES HEAP
void heapify(int a[], int n)
{
for(i=n/2;i>=1;i--)
{
adjust(a,i,n);
}
}
// TO CREATE A HEAP STRUCTURE
void adjust(int a[], int i,int n)
{
j=2*i;
key=a[i];
while(j<=n)
{
if((j<n)&&(a[j]<a[j+1]))
{
j=j+1;
}
if(key>a[j])
{
break;
}
a[j/2]=a[j];
j=2*j;
}
a[j/2]=key;
printf("\nHeap created is:\t");
for(i=1;i<=n;i++)
{
printf("%d\t",a[i]);
}
}
// DISPLAYS SORTED LIST
void display(int a[], int n)
{
for(i=1;i<=n;i++)
{
printf("\t%d",a[i]);
}
}
OUTPUT
RESULT
Thus heap sort has been implemented using C program.
3.1 SINGLE LINKED LIST IMPLEMENTATION
AIM
To implement single linked list using C program.
ALGORITHM
CREATE A LIST:-
Algorithm for declaration of structure node:
Strut NODE
DATA:Data Field
LINK:Link Field (Address of next struct node)
End Struct
Algorithm for CREATELIST()
CREATELIST()
HEAD, LAST, NEWNODE : NODE
Step 1: Set NEWNODE = GETNODE()
Step 2: CALL READNODE(NEWNODE)
Step 3: Set HEAD=NEWNODE
Step 4: Set LAST =NEWNODE
Step 5: If you want to add another node proceed otherwise Stop
Step 6: Set NEWNODE = GETNODE()
Step 7: CALL READNODE(NEWNODE)
Step 8: Assign LAST->Link=newnode
Step 9: Assign LAST=LAST->LINK
Step 10: Goto STEP 5
END CREATELIST()
INSERTION OF A NODE:-
Inserting as a First node in the List:
Insert First(Head:Node)
Newnode:Node
Step 1: Set NEWNODE=GETNODE()
Step 2: CALL READNODE(NEWNODE)
Step 3: If(HEAD==NULL)
Set HEAD =NEWNODE
Return
[End of if structure]
Step 4: Assign NEWNODE->LINK=HEAD
Step 5: Assign HEAD=NEWNODE
END INSERT_FIRST()
Inserting a last node in the list:
INSERT_LAST(HEAD:NODE)
LAST,NEWNODE:NODE
Step 1: Set NEWNODE=GETNODE()
Step 2: CALL READNODE(NEWNODE)
Step 3: If(HEAD==NULL)
Set HEAD =NEWNODE
Return
[End of if structure]
Step 4:Set LAST=HEAD
Step 5: Repeat while(LAST->LINK!=NULL)
Assign LAST->LINK=NEWNODE
[End of while structure]
Step 6: Assign LAST->LINK=NEWNODE
END INSERT_LAST()
Inserting an Intermediate node in the list:
INSERT_MIDDLE(HEAD:NODE)
LAST,NEWNODE:NODE;
CONDITION: Data of any one node in the list for insert
Step 1: Set NEWNODE=GETNODE()
Step 2: CALL READNODE(NEWNODE)
Step 3: If(HEAD==NULL)
Set HEAD =NEWNODE
Return
[End of if structure]
Step 4: Print, “Enter the data of node after which the insertion is to be
made”
Step 5: READ CONDITION
Step 6: Set LAST=HEAD
Step 7: Repeat while(LAST!=NULL)
Step 8: If(LAST->DATA==CONDITION) then
Assign NEWNODE->LINK=LAST->LINK
Assign LAST->LINK=NEWNODE
Return
Else
Assign LAST=LAST->LINK
[End of if structure]
Step 9: [End of step 7 while structure]
Step 10: Print ,”CONDITION IS NOT POSSIBLE”
END INSERT_MIDDLE()
MODIFICATION OF A NODE:
MODIFY_NODE(HEAD:NODE)
Step 1: If(HEAD==NULL)
Return
[End of if structure]
Step 2: Print “Enter the data of node to be modified”
Step 3: READ CONDITION
Step 4: Set LAST=HEAD
Step 5: Repeat while(LAST!=NULL)
Step 6: If(LAST->DATA==CONDITION) then
READ,LAST->DATA
Return
Else
Assign LAST=LAST->LINK
[End of if structure]
Step 7: [End of Step 5 while structure]
Step 8: Printf,”CONDITION IS NOT AVAILABLE”
END MODIFY_NODE()
DELETE OF A NODE:
Algorithm for releasing the memory for the node to be deleted:
RELEASE_NODE(NEWNODE:NODE)
Step 1: Deallocate the space for the node of newnode
Step 2: Return
End RELEASENODE()
Deleting the first node from the list:
DELETE_FIRST(HEAD:NODE)
DELNODE:NODE
Step 1: If(HEAD==NULL)
Print “List is empty”
Return
[End of if structure]
Step 2: Set DELNODE=HEAD
Step 3: Assign HEAD=HEAD->LINK
Step 4: print “Deleted data is”, DELNODE->DATA
Step 5: CALL RELEASENODE(DELNODE)
END DELETE_FIRST()
Deleting the last node from the list:
DELETE_LAST(HEAD:NODE)
LAST,PREV,DELNODE:NODE
Step 1: If(HEAD==NULL)
Print “List is empty”
Return
Step 2: If(HEAD->LINK==NULL) THEN
Set DELNODE=HEAD
Set HEAD=NULL
Print “Deleted Data is”,DELNODE->DATA
Return
[End of if structure]
Step 3: Set LAST=HEAD
Step 4: Repeat while(LAST->LINK!=NULL)
Step 5: Assign PREV=LAST
Step 6: Assign LAST=LAST->LINK
Step 7: [End of step 4 while loop]
Step 8: Set DELNODE=LAST
Step 9: PREV->LINK=NULL
Step 10: Print “Deleted data is”, DELNODE->DATA
Step 11: CALL RELEASENODE(DELNODE)
END DELETE_LAST()
Deleting an intermediate node from the list:
DELETE_MIDDLE(HEAD:NODE)
LAST,PREV,DELNODE:NODE
Step 1: If(HEAD==NULL)
Print “List is empty”
Return
[End of if structure]
Step 2: print “Enter the data of the node in the list for deletion”
Step 3: Read DELDATA
Step 4: If(HEAD->DATA==DELDATA) then
Set DELNODE=HEAD
Assign HEAD=HEAD->LINK
Print “Deleted data is”, DELNODE->DATA
CALL RELEASENODE(DELNODE)
Return
[End of if structure]
Step 5: Set LAST=HEAD->LINK
Step 6: PREV=HEAD
Step 7: Repeat while(LAST!=NULL)
Step 8: If(LAST->DATA==DELDATA) then
Set DELNODE=LAST
Assign PREV->LINK=LAST->LINK
Print “The deleted data is”, DELNODE->DATA
CALL RELEASENODE(DELNODE)
Return
Else
Assign LAST=LAST->LINK
Assign PREV=PREV->LINK
[End of if structure]
Step 9: [End of Step 7 while loop]
Step 10: print “DELDATA is not available in the list”
END DELETE_MIDDLE()
TRAVERSAL OF A LIST:
VIEW_LIST(HEAD:NODE)
Step 1: If(HEAD==NULL)
Print “List is empty”
Return
[End of if structure]
Step 2: while(HEAD!=NULL)
Step 3: print “The data is”, HEAD ->DATA
Step 4: HEAD=HEAD->LINK
Step 5: [End of step 2 while structure]
END VIEW_LIST()
COUNT THE NUMBER OF NODES IN THE LIST:
COUNT_LIST(HEAD:NODE)
COUNT:INTEGER
Step 1: Set COUNT=0
Step 2: If(HEAD=NULL)
Print, “List if Empty”
Return COUNT
Step 3: while(HEAD!=NULL)
Step 4: COUNT=COUNT+1
Step 5: HEAD=HEAD->LINK
Step 6: [End of Step 2 while structure]
Step 7: Return COUNT
END COUNT_LIST()
SOURCE CODE
// SINGLE LINKED LIST IMPLEMENTATION
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head=NULL,*tail=NULL,*newnode,*p;
void append(); // Append
void insert(); // to insert an element
void del(); // to delete an element
void display();
void append()
{
int value;
printf("\nEnter data to append: ");
scanf("%d",&value);
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=value;
newnode->next=NULL;
if(head==NULL)
{
head=newnode;
}
else
{
tail->next=newnode;
}
tail=newnode;
printf("\nData Appended.");
}
void insert()
{
int value,pos,i;
struct node *newnode,*prevnode;
printf("\nEnter data to insert: ");
scanf("%d",&value);
printf("\nEnter the position: ");
scanf("%d",&pos);
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=value;
p=head;
if(pos==1)
{
newnode->next = head;
head = newnode;
}
else
{
for(i=1;i<pos;i++)
{
prevnode = p;
p=p->next;
}
prevnode->next = newnode;
newnode->next = p;
}
printf("\nElement inserted\n");
}
void del()
{
int pos,i;
struct node *newnode,*prevnode;
printf("Enter the position: ");
scanf("%d",&pos);
p=head;
if(pos==1)
{
head = p->next;
free(p);
}
else
{
for(i=1;i<pos;i++)
{
prevnode = p;
p=p->next;
}
prevnode->next = p->next;
if(p->next == NULL) // delete last node
{
tail = prevnode;
}
free(p);
printf("\n Element delete\n");
}
}
void display()
{
p=head;
printf("\nThe List elements: ");
while(p!=NULL)
{
printf(" %d -> ",p->data);
p=p->next;
}
printf("NULL\n");
}
// Main function
void main()
{
int choice;
do
{
printf("\n---------------------------------------------");
printf("\nSINGLE LINKED LIST\n\n");
printf(" 1.APPEND \n 2.INSERT \n 3.DELETE \n 4.DISPLAY \n
5.EXIT \n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
append();
display();
break;
case 2:
insert();
display();
break;
case 3:
del();
display();
break;
case 4:
display();
break;
case 5:
exit(0);
}
}while(choice<=4);
}
OUTPUT
RESULT
Thus single linked list has been implemented using C program.
3.2 DOUBLY LINKED LIST IMPLEMENTATION
AIM
To implement doubly linked list using C program.
ALGORITHM
Procedure DOUBINS(L,R,M,X)
Variables used:
L left most node address
R right most node address
NEWNew node address to be inserted
LPTRLeft link of a node
RPTRRight link of a node
INFOInformation field of the node
NODEName of an element of the list
M Pointer variable
X It contains information to be entered in the node
1. [Obtain new node from availability stack]

NEW NODE
2. [Copy information field]

INFO(NEW) X
3. [Insertion into an empty list?]

If R = NULL
Then LPTR(NEW) RPTR(NEW) NULL
L R NEW
Return
4. [Left most insertion?]

If M = L
Then LPTR(NEW) NULL
RPTR(NEW) M
LPTR(M) NEW
L NEW
Return
5. [Insert in middle]

LPTR(NEW) LPTR(M)
RPTR(NEW) M
LPTR(M) NEW
RPTR(LPTR(NEW)) NEW
Return
Procedure DOUBDEL(L, R, OLD)
Variables used:
LLeft most node
RRight most node
LPTR Left link of a node
RPTR Right link of a node
OLD The address of the node to be deleted
1. [Underflow?]

If R = NULL
Then Write(„UNDERFLOW‟)
Return
2. [Delete node]

If L = R (Single node in list)


Then L RNULL
Else IF OLD = L (Left most node being deleted)
Then L RPTR(L)
LPTR(L) NULL
Else If OLD = R (Right most node being deleted)
Then R LPTR(R)
RPTR(R) NULL
Else RPTR(LPTR(OLD)) RPTR(OLD)
LPTR(RPTR(OLD)) LPTR(OLD)
3. [Return deleted node]

Restore(OLD)
Return
SOURCE CODE
// DOUBLY LINKED LIST IMPLEMENTATION
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *prev,*next;
};
struct node *head=NULL,*tail=NULL,*newnode,*p;
void append(); // Append
void insert(); // to insert an element
void del(); // to delete an element
void displayforward();
void displaybackward();
void append()
{
int value;
printf("Enter data to append: ");
scanf("%d",&value);
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=value;
newnode->next=NULL;
if(head==NULL)
{
newnode->prev = NULL;
head=newnode;
}
else
{
tail->next=newnode;
newnode->prev = tail;
}
tail=newnode;
printf("\nData Appended.");
}
void insert()
{
int value,pos,i;
printf("Enter data to insert: ");
scanf("%d",&value);
printf("Enter the position: ");
scanf("%d",&pos);
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=value;
p=head;
if(pos==1)
{
head = newnode;
newnode->prev = NULL;
newnode->next = p;
}
else
{
for(i=1;i<pos;i++)
{
p=p->next;
}
newnode->prev = p->prev;
newnode->next = p;
p->prev->next = newnode;
p->prev = newnode;
}
printf("\nElement inserted\n");
}
void del()
{
int pos,i;
printf("Enter the position: ");
scanf("%d",&pos);
p=head;
if(pos==1)
{
head = p->next;
head->prev = NULL;
free(p);
}
else
{
for(i=1;i<pos;i++)
{
p=p->next;
}
//Last node
if (p->next == NULL)
{
p->prev->next = NULL;
tail = p->prev;
}
else
{
p->prev->next = p->next;
p->next->prev = p->prev;
}
free(p);
printf("Element delete\n");
}
}
// Display the elements from top
void displayforward()
{
if(head==NULL)
{
printf("The List is empty");
}
else
{
p=head;
printf("The contents of the list are:\n");
while(p!=NULL)
{
printf(" %d -> ", p->data);
p=p->next;
}
printf("null");
}
}
// Display the elements from bottom
void displaybackward()
{
if(head==NULL)
{
printf("The List is empty");
}
else
{
p=tail;
printf("The contents of the list are:\n");
while(p!=NULL)
{
printf(" %d -> ",p->data);
p=p->prev;
}
printf("null");
}
}
// Main function
void main()
{
int choice;
do
{
printf("\n---------------------------------------------");
printf("\nDOUBLY LINKED LIST\n\n");
printf(" 1.APPEND \n 2.INSERT \n 3.DELETE \n 4.DISPLAY
FORWARD \n 5.DISPLAY BACKWARD \n 6.EXIT \n");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1:
append();
displayforward();
break;
case 2:
insert();
displayforward();
break;
case 3:
del();
displayforward();
break;
case 4:
displayforward();
break;
case 5:
displaybackward();
break;
case 6:
exit(0);
}
}while(choice<=5);
}
OUTPUT
RESULT
Thus the doubly linked list has been implemented using C program.
3.3 STACK USING LINKED LIST REPRESENTATION
AIM
To implement stack using linked list using C program.
ALGORITHM
Step 1: Start the program.
Step 2: Declare the Stack data structure using pointer.
Step 3: Implement stack and read the choice of operation.
Step 4: Enter the elements to push into the stack.
Step 5: If the next space of the stack is found to be NULL then declare
top of the
stack is empty, create a new node and make the top of the as new
node.
Step 6: If the top of the stack is found to be full pop out the element
from the stack.
Step 7: If the top of the stack is found to be empty, print “the stack is
empty”
otherwise display the stack.
Step 8: Exit the stack.
Step 9: Stop the program.
SOURCE CODE
// STACK USING LINKED LIST REPRESENTATION
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
struct node
{
int data;
struct node *next;
}*top=NULL;
void push(); // to insert an element
void pop(); // to delete an element
void display(); // to show the stack
// PUSH Operation
void push()
{
int value;
struct node *newnode;
printf("Enter a number to insert: ");
scanf("%d", &value);
newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=value;
if(top==NULL)
{
top=newnode;
newnode->next=NULL;
}
else
{
newnode->next=top;
top=newnode;
}
printf("\nData Inserted.");
}
// POP Operation
void pop()
{
struct node *temp;
if(top==NULL)
{
printf("\nThe stack is empty!");
return;
}
printf("\nPoped value is %d",top->data);
temp=top;
top=top->next;
free(temp);
}
// Show stack
void display()
{
struct node *ptr=top;
printf("\nThe stack is: ");
while(ptr!=NULL)
{
printf("\n%d", ptr->data);
ptr=ptr->next;
}
printf("\nNULL\n");
}
// Main function
void main()
{
int choice;
clrscr();
do
{
printf("\n---------------------------------------------");
printf("\n\t\tSTACK USING LINKED LIST\n\n");
printf("1:PUSH\n2:POP\n3:DISPLAY\n4:EXIT\n");
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{
case 1:
push();
display();
break;
case 2:
pop();
display();
break;
case 3:
display();
break;
case 4:
exit(0);
}
}while(choice<=4);
}
OUTPUT
RESULT
Thus stack using linked list has been implemented using C program.
3.4 QUEUE USING LINKED LIST IMPLEMENTATION
AIM
To implement queue using linked list using C program.
ALGORITHM
Step 1: Start the program.
Step 2: Declare the Queue data structure using pointer.
Step 3: Create a node and read the first element along with the link to
another
node.
Step 4: Read the element to be inserted by allocating memory. If the
new
element is inserted, print “The element is inserted ”.
Step 5: Perform delete operation and print “the node is deleted”.
Step 6: Display the elements in the list.
Step 7: Exit the Linked queue.
Step 8: Stop the program.
SOURCE CODE
// QUEUE USING LINKED LIST IMPLEMENTATION
#include<stdio.h>
#include<stdlib.h>
#include<stdio.h>
struct node
{
int data;
struct node *next;
};
struct node *front=NULL,*rear=NULL,*newnode,*ptr;
void enqueue(); // to insert an element
void dequeue(); // to delete an element
void display(); // to show the stack
// PUSH Operation
void enqueue()
{
int value;
printf("Enter a number to insert: ");
scanf("%d",&value);
newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=value;
newnode->next=NULL;
if(front==NULL)
{
front=newnode;
rear=newnode;
}
else
{
rear->next=newnode;
rear=newnode;
}
printf("\nData Inserted.");
}
// POP Operation
void dequeue()
{
struct node *temp;
if(front==NULL)
{
printf("\nThe queue is empty!");
return;
}
else
{
printf("\nPoped value is %d",front->data);
temp=front;
if(front==rear)
{
front=NULL;
rear=NULL;
}
else
{
front=front->next;
}
free(temp);
}
}
// Show stack
void display()
{
ptr=front;
printf("\nThe queue is: \n");
while(ptr!=NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
printf("NULL\n");
}
// Main function
void main()
{
int choice;
do
{
printf("\n---------------------------------------------");
printf("\n\t\tQUEUE USING LINKED LIST\n\n");
printf("1:ENQUEUE\n2:DEQUEUE\n3:DISPLAY\n4:EXIT\n");
printf("\nEnter your choice: \t");
scanf("%d",&choice);
switch(choice)
{
case 1:
enqueue();
display();
break;
case 2:
dequeue();
display();
break;
case 3:
display();
break;
case 4:
exit(0);
}
}while(choice<=4);
}
OUTPUT
RESULT
Thus queue using linked list has been implemented using C program.
4.1 ARRAY IMPLEMENTATION OF STACK
AIM
To perform array implementation of stack using C program.
ALGORITHM
Push Operation:
Void push(stack,top,maxstk,item)
Step 1:(stack is already filled?)
If top=maxstk then
print stack overflow and return
Step 2: Else
set top=top+1;
Step 3: set stack[top]=item
Step 4: return
End
Pop Operation:
Begin
Pop(stack,top,item)
Step 1: (is there is an item in stack for removal)
If top=-1 then
print stack is underflow and return
Step 2: else set item=stack[top]
Step 3: set top=top-1
Step 4:retuen
End
SOURCE CODE
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int choice,n,a[30],top=-1,i;
void push(); // TO INSERT THE ELEMENT INTO THE STACK
void pop(); // TO DELETE THE ELEMENT FROM THE STACK
void peek(); // TO RETURN THE TOP VALUE OF THE STACK
void display();
void main()
{
//clrscr();
printf("\n ARRAY IMPLEMENTATION OF STACK");
do
{
printf("\nMain menu");
printf("\n1.Stack
creation\n2.Push\n3.Pop\n4.Peek\n5.Display\n6.Exit\n");
printf("\nEnter your choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the stack size:");
scanf("%d",&n);
break;
case 2:
push();
display();
break;
case 3:
pop();
display();
break;
case 4:
peek();
display();
break;
case 5:
display();
break;
case 6:
exit(1);
}
}while(choice<=6);
getch();
}
void push()
{
if(top==n-1)
{
printf("\nThe stack is full\n");
}
else
{
printf("\nEnter the element to insert:");
top++;
scanf("%d",&a[top]);
}
}
void pop()
{
if (top==-1)
{
printf("\nThe stack is empty");
}
else
{
printf("\n The element popped is %d\n",a[top]);
top--;
}
}
void peek()
{
if (top==-1)
{
printf("\nThe stack is empty");
}
else
{
printf("\n The top element is %d\n",a[top]);
}
}
void display()
{
if (top==-1)
{
printf("\nThe stack is empty");
}
else
{
printf("\nThe stack elements are\n");
for(i=top;i>=0;i--)
{
printf("\t%d",a[i]);
}
}
}
OUTPUT
RESULT
Thus the array implementation of stack is performed using C program.
4.2 EVALUATING ARITHMETIC EXPRESSION
AIM
To implement evaluation of arithmetic expression using C program.
ALGORITHM
1. A string INFIX containing the infix expression
2. A stack opstk, which may contain:
- All arithmetic operators
- Parenthesis " (“ and “) "
- Null character " \O "
3. A string POSTFIXES containing the final postfix expression.
4. Push ' \o ' out OPSTACK as its first entry
5. Read the next character CH from the INFIX string
6.Test CH and:
- If CH is an operand, append it to the POSTFIX string
- If CH is a left parenthesis, then push CH onto the stack

- If CH is a right parenthesis. then pop entries from stack and append


them to POSTFIX until a left parenthesis is popped. Discard both left
and right parentheses.
- If CH is ' \o ', pop all entries that remain on the stack and append
them to the POSTFIX string
- Otherwise, pop from the stack and append to the POSTFIX string ,
whose STACK - PRIORITY is greater than or equal to the INFIX -
PRIORITY of CH. Then stack CH.
7. Repeat step (4) and (5) until CH becomes ' \o „.
SOURCE CODE
// EVALUATING ARITHMETIC EXPRESSION
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<conio.h>
int top;
int stack[100];
int i, n;
int x, y, result, value;
char postfix[100];
char item;
int data[100];
void get();
void push(int);
int pop();
int isoperator(char);
void main()
{
clrscr();
get();
getch();
}
// GETS THE NUMBER OF ELEMENTS AND DISPLAYS IT IN
UNSORTED ORDER
void get()
{
int t;
top=-1;
printf("\nEnter the arithmetic expression in Postfix notation:");
gets(postfix);
n=strlen(postfix);
for(i=0;i<n;i++)
{
item=postfix[i];
if(isalpha(item))
{
printf("\nEnter the value of operand: %c \t", item);
scanf("%d",&data[i]);
push(data[i]);
}
else if(isoperator(item))
{
y = pop();
x = pop();
switch(item)
{
case '+':
result = x + y;
break;
case '-':
result = x - y;
break;
case '*':
result = x * y;
break;
case '/':
result = x / y;
break;
}
push(result);
}
else
{
printf("\nInvalid Postfix Expression.\n");
getch();
}
}
value = pop();
printf("\nValue of the postfix expression is %d \t", value);
getch();
}
void push(int item)
{
if(top == 99)
{
printf("\nStack Overflow. Push not possible.\n");
}
else
{
top = top+1;
stack[top] = item;
}
}
int pop()
{
int element;
if(top == -1)
{
printf("\nStack Underflow. Pop not possible.\n");
return(0);
}
else
{
element=stack[top];
top = top-1;
return(element);
}
}
//Function to check whether the symbol is an operator.
int isoperator(char symbol)
{
if(symbol == '*' || symbol == '/' || symbol == '+' || symbol == '-')
{
return 1;
}
else
{
return 0;
}
}
OUTPUT
RESULT
Thus the evaluation of arithmetic expression has been implemented
using C program.
4.3 INFIX EXPRESSION TO POSTFIX EXPRESSION
AIM
To implement infix expression to postfix expression conversion using
C program.
ALGORITHM
1. A string INFIX containing the infix expression
2. A stack opstk, which may contain:
- All arithmetic operators
- Parenthesis " (“ and “) "
- Null character " \O "
3. A string POSTFIXES containing the final postfix expression.
4. Push ' \o ' out OPSTACK as its first entry
5. Read the next character CH from the INFIX string
6.Test CH and:
- If CH is an operand, append it to the POSTFIX string
- If CH is a left parenthesis, then push CH onto the stack

- If CH is a right parenthesis. then pop entries from stack and append


them to POSTFIX until a left parenthesis is popped. Discard both left
and right parentheses.
- If CH is ' \o ', pop all entries that remain on the stack and append
them to the POSTFIX string
- Otherwise, pop from the stack and append to the POSTFIX string ,
whose STACK - PRIORITY is greater than or equal to the INFIX -
PRIORITY of CH. Then stack CH.
7. Repeat step (4) and (5) until CH becomes ' \o „.
SOURCE CODE
#define MAX 50
char infix[MAX], postfix[MAX], Stack[MAX];
char element;
void push(char);
int pop();
void checkStack(int);
int p=-1,top=-1;
void main()
{
int i,op;
puts("Enter the infix expression with single character variables and
operators");
gets(infix);
push('('); //Insert a dummy left parenthesis
for(i=0;infix[i] != '\0';i++)
{
if(isalpha(infix[i]))
{
postfix[++p] = infix[i];
}
else
{
op = 0;
switch(infix[i])
{
case '*':
op = 1;
break;
case '/':
op = 1;
break;
case '+':
op = 2;
break;
case '-':
op = 2;
break;
case '(':
push('(');
break;
case ')':
while((element=pop()) != '(') //Pop from stack and write to postfix
expression till u encounter a left parenthesis
{
postfix[++p] = element;
}
break;
}
if(op==1 || op ==2)
{
checkStack(op);
push(infix[i]);
}
}
}
while((element=pop()) != '(' )
{
postfix[++p] = element;
}
puts(postfix);
getch();
}
void checkStack(int op)
{
int opStack;
do
{
switch(Stack[top])
{
case '*':
opStack = 1;
break;
case '/':
opStack = 1;
break;
case '+':
opStack = 2;
break;
case '-':
opStack = 2;
break;
case '(':
opStack = 3;
}
if(opStack <= op ) //If the operator at the top of the stack is of equal or
higher precedence
{
postfix[++p] = pop();
}
}
while(op >= opStack);
}
void push(char element)
{
if(top == MAX-1)
{
printf("Stack Overflow");
}
else
{
Stack[++top] = element;
}
}
int pop()
{
int element;
if(top == -1)
{
printf("Stack Underflow");
element = -999;
}
else
{
element = Stack[top--];
}
return(element);
}
OUTPUT
RESULT
Thus the infix expression to postfix expression conversion has been
implemented using C program.
5 BINARY TREE TRAVERSAL
AIM
To implement binary tree traversal using C program.
ALGORITHM
Preorder
sub P(TreeNode)
Output(TreeNode.value)
If LeftPointer(TreeNode) != NULL Then
P(TreeNode.LeftNode)
If RightPointer(TreeNode) != NULL Then
P(TreeNode.RightNode)
end sub
In-order
sub P(TreeNode)
If LeftPointer(TreeNode) != NULL Then
P(TreeNode.LeftNode)
Output(TreeNode.value)
If RightPointer(TreeNode) != NULL Then
P(TreeNode.RightNode)
end sub
Post-order
sub P(TreeNode)
If LeftPointer(TreeNode) != NULL Then
P(TreeNode.LeftNode)
If RightPointer(TreeNode) != NULL Then
P(TreeNode.RightNode)
Output(TreeNode.value)
end sub
SOURCE CODE
#include<stdlib.h>
#include<stdio.h>
#include<conio.h>
struct tree
{
int data;
struct tree *left,*right;
};
struct tree *head=NULL, *newnode;
void makenode(int);
void insert(struct tree*, int);
void inorder(struct tree*);
void preorder(struct tree*);
void postorder(struct tree*);
// Make a node
void makenode(int value)
{
newnode= (struct tree*)malloc(sizeof(struct tree));
newnode->data=value;
newnode->left=NULL;
newnode->right=NULL;
}
// Insert a data
void insert(struct tree* node, int value)
{
if(value == node->data)
{
printf("Duplicate Elements \n");
}
else if(value < node->data)
{
if (node->left == NULL)
{
node->left = newnode;
}
else
{
insert(node->left, value);
}
}
else
{
if(node->right == NULL)
{
node->right = newnode;
}
else
{
insert(node->right, value);
}
}
}
// Display the data
void inorder(struct tree* node)
{
if( node == NULL)
{
return;
}
inorder(node->left);
printf(" %d ",node->data);
inorder(node->right);
}
// Display the data
void preorder(struct tree* node)
{
if( node == NULL)
{
return;
}
printf(" %d ",node->data);
preorder(node->left);
preorder(node->right);
}
// Display the data
void postorder(struct tree* node)
{
if( node == NULL)
{
return;
}
postorder(node->left);
postorder(node->right);
printf(" %d ",node->data);
}
void main()
{
int value,ch;
clrscr();
do
{
printf("\n --- Binary Search Tree --- \n ");
printf("1.Create \n 2.Insert \n 3.InOrder \n 4.PreOrder \n 5.PostOrder \n
6.Exit \n");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
if(head != NULL)
{
printf("Root already created\n");
break;
}
printf("Enter the data:");
scanf("%d",&value);
makenode(value);
head = newnode;
printf("Root data created\n");
break;
case 2:
printf("Enter the data:");
scanf("%d",&value);
makenode(value);
insert(head,value);
inorder(head);
break;
case 3:
inorder(head);
break;
case 4:
preorder(head);
break;
case 5:
postorder(head);
break;
}
}while(ch != 6);
}
OUTPUT
RESULT
Thus the binary tree traversal has been implemented using C program.
6.1 GRAPH TRAVERSAL : BREADTH FIRST SEARCH
AIM
To implement graph traversal - breadth first search using C program.
ALGORITHM
Breadth-first search
Input: A graph G and a root v of G
Output: The node closest to v in G satisfying some conditions, or null if
no such a node exists in G
1 procedure BFS(G,v):
2 create a queue Q
3 enqueue v onto Q
4 mark v
5 while Q is not empty:
6 t ← Q.dequeue()
7 if t is what we are looking for:
8 return t
9 for all edges e in G.adjacentEdges(t) do
12 o ← G.adjacentVertex(t,e)
13 if o is not marked:
14 mark o
15 enqueue o onto Q
16 return null
SOURCE CODE
#include<stdio.h>
#include<conio.h>
int n,edge[10][10],visit[10],queue[100],front,rear,v;
void Initial(int n)
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
edge[i][j]=0; // No edge
}
}
for(i=1;i<=n;i++)
{
visit[i] = 0; // Not visited
}
}
void BFS(int v)
{
int i,t;
front = 0;
rear= 0;
printf("Visitied vertices\n");
printf("%d",v);
visit[v]=1;
while(front <= rear)
{
for(i=1;i<=n;i++)
{
if(edge[v][i]==1 && visit[i]==0)
{
printf("\t%d",i);
visit[i]=1;
queue[rear++]=i;
}
}
v=queue[front++];
}
}
void main()
{
int i,j,k,m;
clrscr();
printf("Enter Number of vertices & Edges \n");
scanf("%d",&n);
scanf("%d",&m);
Initial(n);
printf("\n Enter any two vertex IDs where an edge exist \n");
for(k=1;k<=m;k++)
{
scanf("%d%d",&i,&j);
edge[i][j]=1;
edge[j][i]=1;
}
printf("enter initial vertex ");
scanf("%d",&v);
BFS(v);
getch();
}
OUTPUT
1
2
3
4
RESULT
Thus the graph traversal - breadth first search has been implemented
using C program.
6.2 GRAPH TRAVERSAL : DEPTH FIRST SEARCH
AIM
To implement graph traversal - depth first search using C program.
ALGORITHM
Depth-first search
Input: A graph G and a vertex v of G
Output: A labeling of the edges in the connected component of v as
discovery edges and back edges
1 procedure DFS(G,v):
2 label v as explored
3 for all edges e in G.incidentEdges(v) do
4 if edge e is unexplored then
5 w ← G.adjacentVertex(v,e)
6 if vertex w is unexplored then
7 label e as a discovery edge
8 recursively call DFS(G,w)
9 else
10 label e as a back edge
SOURCE CODE
int n,edge[10][10],visit[10],v;
void Initial(int n)
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
edge[i][j]=0; // No edge
}
}
for(i=1;i<=n;i++)
{
visit[i] = 0; // Not visited
}
}
void DFS(int v)
{
int i;
for(i=1;i<=n;i++)
{
if(edge[v][i]==1 && visit[i]==0)
{
printf("\t%d",i);
visit[i]=1;
DFS(i);
}
}
}
void main()
{
int i,j,k,m;
printf("Enter Number of vertices & Edges \n");
scanf("%d",&n);
scanf("%d",&m);
Initial(n);
printf("\n Enter any two vertex IDs where an edge exist \n");
for(k=1;k<=m;k++)
{
scanf("%d%d",&i,&j);
edge[i][j]=1;
edge[j][i]=1;
}
printf("Enter initial vertex ");
scanf("%d",&v);
printf("Traversal as per DFS strategy \n");
printf("%d",v);
visit[v]=1;
DFS(v);
getch();
}
OUTPUT
1
3
2
5
4
6
RESULT
Thus the graph traversal - depth first search has been implemented
using C program.
7.1 MINIMUM SPANNING TREE: PRIM’S ALGORITHM
AIM
To implement minimum spanning tree: Prim‟s Algorithm using C
program.
ALGORITHM
Void prim(Graph G)
{
MSTTREE T;
Vertex u,v;
Set of vertices V;
Set of tree vertices U;
T=Null;
U={1}
While(U!=V)
{
Let (u,v)be a lowest cost such that u is in U and v is in V-U;
T=TU{(u,v)};
U=UU{v};
}
}
Void prims (Table T)
{
Vertex V,W;
For (i=0;i<Numvertex;i++)
{
T[i].known=false; int
T[i].dist=incinity; min,
T[i].path=0; minco
} st;
For(;;) void
{ getdat
Let Vbe the start vertex with the smallest distance a();
T[v].dist=0; void
T[v].known=Trie; prim(i
For each W adjacent to V
nt,int);
If(!T[w].known)
void
{
displa
T[w].Dist=Min(T[W].Dist,Cvw);
T[W].path=V; y();
}
}
}
SOURCE CODE
#include<stdio.h>
#include<conio.h>
int n,i,j,k,l,near1[50];
int cost[50][50],t[50][50];
void main()
{
clrscr();
getdata();
display();
getch();
}
//GETS THE INPUT
void getdata()
{
min=9999;
printf("\nPRIMS ALGORITHM\n");
printf("\nEnter the number of elements:");
scanf("%d",&n);
printf("\nIf there is no edge then enter 9999\n");
for(i=1;i<=n;i++)
{
for(j=i;j<=n;j++)
{
if(i!=j)
{
printf("\nThe cost between %d and %d :",i,j);
scanf("%d",&cost[i][j]);
cost[j][i]=cost[i][j];
if(cost[i][j]<min)
{
min=cost[i][j];
k=i;
l=j;
}
}
else
{
cost[i][j]=9999;
}
}
}
//DISPLAYS THE ADJACENCY MATRIX OF THE GRAPH
printf("\nThe adjacency matrix is:\n ");
for(i=1;i<=n;i++)
{
printf("\n");
for(j=1;j<=n;j++)
{
printf("\t%d",cost[i][j]);
}
}
prim(k,l);
}
//FINDS THE MINIMUM SPANNING TREE AND MINIMUM COST
void prim(int k, int l)
{
mincost=cost[k][l];
t[1][1]=k;
t[1][2]=l;
for(i=1;i<=n;i++)
{
if(cost[i][l]<cost[i][k])
{
near1[i]=l;
}
else
{
near1[i]=k;
}
}
near1[l]=0;
near1[k]=0;
for(i=2;i<n;i++)
{
min=9999;
for(int a=1;a<=n;a++)
{
if((near1[a]!=0)&&(min>cost[a][near1[a]]))
{
min=cost[a][near1[a]];
j=a;
}
}
t[i][1]=j;
t[i][2]=near1[j];
mincost=mincost+min;
near1[j]=0;
for(k=1;k<=n;k++)
{
if((near1[k]!=0)&&(cost[k][near1[k]]>cost[k][j]))
{
near1[k]=j;
}
}
}
}
//PRINTS THE EDGES IN MINIMUM SPANNING TREE
void display()
{
printf("\nMinimum Cost is : %d",mincost);
printf("\nThe Minimum Spanning Tree is : \n");
for(i=1;i<n;i++)
{
printf("%d -> %d \n",t[i][1],t[i][2]);
}
}
OUTPUT
2 has
1 be
en
5 im
3 ple
4 m
en
6 te
20 d
15 us
30 in
18 g
5 C
3 pr
25 og
12 ra
5 m.
R
E
S
U
L
T
Th
us
th
e
gr
ap
h
tra
ve
rs
al
-
de
pt
h
fir
st
se
ar
ch
7. m Int (E ++
2 u Ed dg ;
M m ge es Se
IN sp sA Ac tU
I an cc ce ni
M ni ep pte on
U ng te d< (S,
M tre d= Nu Us
S e: 0; m et,
Di Ve Vs
P Kr
sjo rte et)
A us
int x- ;
N ka
Se 1)
NI l‟s t {
N Al S; E=
G go He De
T rit ap let
R h H; e
E m Ve Mi
E: us rte n(
K in x H)
R g U, ;
U C V; Us
S pr Se et=
K og tT Fi
A ra yp nd
L’ m. eU (U,
S A set S);
A L , Vs
L G Vs et=
G O et; Fi
O RI Ed nd
ge (V,
RI T
E; S);
T H
Ini If(
H M tia Us
M V
liz et!
AI oi
e( =V
M d
S); set
To kr
Bu )
im us
ild {
pl ka
He Ed
e l(
ap ge
m Gr
(H sA
en ap
); cc
h
t W ept
G)
mi hil ed
{
ni e
} S R C D
} O C O E
} U E
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define MAX 50
#define INFINITY 9999
int a[50][50],edge[50][50],n;
int visited[50],maxedges,visit,minorigin,mindesti;
void initialvalue();
void getValue();
void display();
void kruskal();
void main()
{
initialvalue();
getValue();
display();
kruskal();
getch();
}
void getValue()
{
int i,wt,origin,destin;
printf("Enter the number of nodes:");
scanf("%d",&n);
maxedges=n*(n-1)/2;
for(i=1;i<=maxedges;i++)
{
printf("Enter the node IDs where edge exist (0 0 to quit) : ");
scanf("%d %d", &origin, &destin);
if((origin==0) && (destin==0))
{
break;
}
printf("Enter the distance between two nodes ");
scanf("%d", &wt);
a[origin][destin]=wt;
a[destin][origin]=wt;
}
}
void display()
{
int i,j;
printf("Adjacency Matrix \n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%6d", a[i][j]);
}
printf("\n");
}
}
void initialvalue()
{
int i,j;
for(i=1;i<MAX;i++)
{
visited[i] = 0;
}
for(i=1;i<MAX;i++)
{
for(j=1;j<MAX;j++)
{
edge[i][j]=INFINITY;
a[i][j]=INFINITY;
}
}
}
void kruskal()
{
int i,j;
int miniedge;
while(1)
{
miniedge = MAX-1;
minorigin=MAX-1;
mindesti=MAX-1;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
if(visited[i] == 1 && visited[j]) // Avoid cycle
{
continue;
}
if(a[i][j] < miniedge)
{
miniedge =a[i][j]; // Find the smaller edge
minorigin=i;
mindesti=j;
}
}
}
if(miniedge == MAX-1) // Visited all nodes
{
return;
}
visited[minorigin] = 1;
visited[mindesti] = 1;
printf("%d -> %d \n", minorigin,mindesti);
}
}
OUTPUT
2
1
5
3
4
6
20
15
30
18
5
3
25
12
15
RESUL
T
Thus the
minimu
m
spannin
g tree:
Kruskal
‟s
Algorith
m has
been
impleme
nted
using C
program
.
8 T[i] T[
SHORT .kn V].
EST ow kn
PATH n= ow
ALGO Fal n=
RITHM se; Tr
: T[i] ue;
DIJKS .dis For
TRA’S t=i eac
nfi h
SHORT
nity W
EST
; adj
PATH T[i] ace
ALGO .pat nt
RITHM h= to
AIM Not V
To A if(!
impleme vert T[
nt ex; w].
Dijkstra } kn
‟s T[s ow
Shortest tart n)
Path ].di
Algorith st=
m using 0;
C For
program (;;)
. {
ALGO V=
RITHM Sm
voidDijk alle
stra(Gra st
ph unk
G,Table no
T) wn
{ dist
Int i; anc
Vertex e
V,W; vert
Read ex;
Graph(G if(v
,T) ==
For Not
(i=0;i<N A
umverte vert
x;i++) ex)
{ bre
ak;
{ SO de 10 vi
T[W].kn UR <c 00 sit
own) CE oni int [1
{ CO o.h n, 0],
T[W].Di DE > co fr
st=Min[ #in #d st[ on
T[w].Dis clu efi 10 t,r
t,T[v].Di de< ne ][ ea
st+Cvw] stdi IN 10 r,v
T[w].pat
o.h FI ],d ;
h=V;
> NI ist
}
#in T [1
}
} clu Y 0],
void Initial(int n)
{
int i,j;
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
cost[i][j] = INFINITY; // No edge
}
}
for(i=1;i<=n;i++)
{
dist[i] = INFINITY;
visit[i] = 0;
}
}
int nearest()
{
int i,node, weight;
weight = INFINITY;
for(i=1;i<=n;i++)
{
if(visit[i] == 0 && dist[i] < weight)
{
weight = dist[i];
node=i;
}
}
return node;
}
void Dijkstra(int v)
{
int i,u,q,alt;
dist[v]=0;
for(i=1;i<=n;i++)
{
u=nearest();
for(v=1;v<=n;v++)
{
if(cost[u][v] == INFINITY) continue;
alt = dist[u] + cost[u][v];
if(alt < dist[v])
{
dist[v] = alt;
}
}
visit[u] = 1;
}
}
void display()
{
int i,j;
printf("Cost Matrix \n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
printf("%d\t", cost[i][j]);
}
printf("\n");
}
}
void main()
{
int i,j,k,m;
printf("Enter the number of vertices \n");
scanf("%d", &n);
Initial(n);
for(i=1;i<=n;i++)
{
for(j=i+1;j<=n;j++)
{
printf("Enter the distance between %d and %d\n" , i, j);
printf("if edge not exist enter 1000 \n");
scanf("%d", &cost[i][j]);
cost[j][i] = cost[i][j];
}
}
display();
printf("\nEnter the source vertex \n");
scanf("%d",&v);
Dijkstra(v);
printf("Result \n");
for(i=1;i<=n;i++)
{
printf("distance of %d is", i );
printf("%d\n",dist[i]);
}
getch();
}
OUTPUT
2
1
5
3
4
6
20
15
30
18
5
3
25
12
15
RESU
LT
Thus
the
Dijks
tra‟s
Short
est
Path
Algo
rithm
has
been
impl
emen
ted
using
C
progr
am.
9a
Clas
s
and
Obje
ct
with
a
Simp
le
Cons
truct
or
and
Dest
ruct
or
Impl
eme
ntati
on
AIM
To implement Class and Object with a Simple Constructor and Destructor using C++ program.
ALGORITHM
1.Start.
2.Declare the class product.
3.Constructor class display constructor method.
4.Destructor to free the memory space allocated.
5.Function to display product.
6.Stop.
SOURCE CODE
// Constructor is a method
// Constructor name should be same as a class
// Constructor method will execute automatically when we create object
#include<iostream.h>
#include<conio.h>
class product //Class Declaration
{
public:
product() //Default Constructor to initialize data member
{
cout<<"\n Constructor method ";
}
~product() //Destructor
{
cout<<"\n Destructor methos ";
}
};
int main()
{
product p1; //Object declaration & Default constructor invoke
getch();
return 0;
}
OUTPUT
RESULT
Thus the implementation of Class and Object with a Simple Constructor and Destructor have
been performed using C++ program.
.
9 b Class and Object with Different Types of Constructor with a Destructor
AIM
To implement Class and Object with Different types of Constructor and a Destructor using C++
program.
ALGORITHM
1.Start
2.Declare the class product and data. member product noand cost.
3.Default constructor to intialize data member
4.Parameterizedcostructor to intialize data member using parameter a and b.
5.Copy constructor to intialize data member by using the adress of the object of parameterized
constructor
6.Destructor to free the memory space allocated product number.
7.to display product details
8.Stop.
SOURCE CODE
#include<iostream.h>
#include<conio.h>
class product //Class Declaration
{
private: //Data Member Declaration
int productno;
float cost;
public:
product()//Default Constructor to initialize data member
{
cout<<"\n\t\tDefault Constructor ";
productno=0;
cost=0.0;
}
product(int a,float b)
//Parameterized Constructor to initialize data member
{
cout<<"\n\t\tParameterized Constructor ";
productno=a;
cost=b;
}
product(product &x) //Copy Constructor to initialize data member
{
cout<<"\n\t\tCopy Constructor ";
productno=x.productno;
cost=x.cost;
}
~product() //Destructor
{
cout<<"\nProduct "<<productno<<"is destroyed\n";
}
void display(void) //Function to display product details
{
cout<<"\nPRODUCT DETAILS";
cout<<"\nProduct Number:"<<productno<<"\n";
cout<<"\nProduct Cost:"<<cost<<"\n";
}
};
int main()
{
//clrscr();
product p1; //Object declaration & Default constructor invoked
p1.display();
product p2(2,125.5); //Object declaration & Parameterized constructor invoked
p2.display();
product p3(p2); //Object declaration & Copy constructor invoked
p3.display();
getch();
return 0;
}
OUTPUT
RESULT
Thus the implementation of Class and Object with Different types of Constructor and a
Destructor have been performed using C++ program.
10 a. Single Inheritance
AIM
To implement the concept of single inheritance using C++ program.
ALGORITHM
• Start the program • Invoke the base class student • Invoke the derived class exam using public derivation
• Get the input data • Create an object for the class exam • Call the member functions
getdata(),calculation(),display() using the object • Display the outputs • Stop the program
SOURCE CODE
// private - Can access in the current class (Not object, Not derived class)
// protected - Can access in the current class and derived class (Not object)
// public - Can access in the current class, derived class and object
// Single Inheritance: A -> B
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student //Class Declaration
{
protected:
int regno,m1,m2,m3,m4,m5; //Data Member Declaration
char name[20],dept[5];
public:
void getdata() //Function to get student details
{
cout<<"\nEnter the register number:";
cin>>regno;
cout<<"\nEnter the name:";
cin>>name;
cout<<"\nEnter the department:";
cin>>dept;
cout<<"\nEnter the mark 1:";
cin>>m1;
cout<<"\nEnter the mark 2:";
cin>>m2;
cout<<"\nEnter the mark 3:";
cin>>m3;
cout<<"\nEnter the mark 4:";
cin>>m4;
cout<<"\nEnter the mark 5:";
cin>>m5;
}
};
class exam: public student //Deriving new class from base class
{
private:
int total; //Data Member Declaration
char result[6];
float average;
public:
void calculation() //Function to calculate result of the student
{
total=m1+m2+m3+m4+m5;
average=float(total)/5;
if(m1>49 && m2>49 && m3>49 && m4>49 && m5>49)
{
strcpy(result,"Pass");
}
else
{
strcpy(result,"Fail");
}
}
void display() //Function to display student details
{
cout<<"\n\t\t\tSTUDENT DETAILS";
cout<<"\nRegister Number:"<<regno;
cout<<"\nName:"<<name;
cout<<"\nDepartment:"<<dept;
cout<<"\nMark 1:"<<m1;
cout<<"\nMark 2:"<<m2;
cout<<"\nMark 3:"<<m3;
cout<<"\nMark 4:"<<m4;
cout<<"\nMark 5:"<<m5;
cout<<"\nTotal:"<<total;
cout<<"\nAverage:"<<average;
cout<<"\nResult:"<<result;
}
};
int main()
{
//clrscr();
exam ex; //Object declaration for derived class
cout<<"\n\t\t\t STUDENT INFORMATION";
ex.getdata(); //Calling Base class function using derived object
ex.calculation();
ex.display();
getch();
return 0;
}
OUTPUT
RESULT
Thus the concept of single inheritance has been implemented using C++ program.
10 b. Multilevel Inheritance
AIM
To implement the concept of multilevel inheritance using C++ program.
ALGORITHM
• Start the program • Invoke the base class student
• Invoke derived class marks derived from the class student • Invoke another derived class result derived
from the class marks • Get the input data • Create an object for the class result • Call the member functions
getdata(),getmarks(),calculation(),display() using the object • Display the outputs • Stop the program
SOURCE CODE
//Multilevel Inheritance: A -> B -> C
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student //Class Declaration
{
protected:
int regno; //Data Member Declaration
char name[20],dept[5];
public:
void getdata() //Function to get student details
{
cout<<"\nEnter the register number:";
cin>>regno;
cout<<"\nEnter the name:";
cin>>name;
cout<<"\nEnter the department:";
cin>>dept;
}
};
class marks: public student //Deriving new class from base class
{
protected:
int m1,m2,m3,m4,m5; //Data Member Declaration
public:
void getmarks() //Function to get student marks
{
cout<<"\nEnter the mark 1:";
cin>>m1;
cout<<"\nEnter the mark 2:";
cin>>m2;
cout<<"\nEnter the mark 3:";
cin>>m3;
cout<<"\nEnter the mark 4:";
cin>>m4;
cout<<"\nEnter the mark 5:";
cin>>m5;
}
};
class result: public marks //Deriving new class from another derived class
{
private:
int total; //Data Member Declaration
float average;
char result[6];
public:
void calculation() //Function to calculate result of the student
{
total=m1+m2+m3+m4+m5;
average=float(total)/5;
if(m1>49 && m2>49 && m3>49 && m4>49 && m5>49)
{
strcpy(result,"Pass");
}
else
{
strcpy(result,"Fail");
}
}
void display() //Function to display student details
{
cout<<"\n\t\t\tSTUDENT DETAILS";
cout<<"\nRegister Number:"<<regno;
cout<<"\nName:"<<name;
cout<<"\nDepartment:"<<dept;
cout<<"\nMark 1:"<<m1;
cout<<"\nMark 2:"<<m2;
cout<<"\nMark 3:"<<m3;
cout<<"\nMark 4:"<<m4;
cout<<"\nMark 5:"<<m5;
cout<<"\nTotal:"<<total;
cout<<"\nAverage:"<<average;
cout<<"\nResult:"<<result;
}
};
int main()
{
clrscr();
result r; //Object declaration for derived class
cout<<"\n\t\t\t STUDENT INFORMATION";
r.getdata(); //Calling Base class function using derived object
r.getmarks(); //Calling Base class function using derived object
r.calculation();
r.display();
getch();
return 0;
}
OUTPUT
RESULT
Thus the concept of multilevel inheritance has been implemented using C program.
10 c. Multiple Inheritance
AIM
To implement the concept of multiple inheritance using C++ program.
ALGORITHM
• Start the program • Invoke the base class student
• Invoke another base class marks • Invoke the derived class result derived from the class student and class
marks • Get the input data • Create an object for the class result • Call the member functions
getdata(),getmarks(),calculation(),display() using the object • Display the outputs • Stop the program
SOURCE CODE
// Multiple Inheritance: A -> C & B -> C
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student //Class Declaration
{
protected:
int regno; //Data Member Declaration
char name[20],dept[5];
public:
void getdata() //Function to get student details
{
cout<<"\nEnter the register number:";
cin>>regno;
cout<<"\nEnter the name:";
cin>>name;
cout<<"\nEnter the department:";
cin>>dept;
}
};
class marks //Class Declaration
{
protected:
int m1,m2,m3,m4,m5; //Data Member Declaration
public:
void getmarks() //Function to get student marks
{
cout<<"\nEnter the mark 1:";
cin>>m1;
cout<<"\nEnter the mark 2:";
cin>>m2;
cout<<"\nEnter the mark 3:";
cin>>m3;
cout<<"\nEnter the mark 4:";
cin>>m4;
cout<<"\nEnter the mark 5:";
cin>>m5;
}
};
class result: public student,public marks //Deriving new class from more two base classes
{
private:
int total; //Data Member Declaration
float average;
char result[6];
public:
void calculation() //Function to calculate result of the student
{
total=m1+m2+m3+m4+m5;
average=float(total)/5;
if(m1>49 && m2>49 && m3>49 && m4>49 && m5>49)
{
strcpy(result,"Pass");
}
else
{
strcpy(result,"Fail");
}
}
void display() //Function to display student details
{
cout<<"\n\t\t\tSTUDENT DETAILS";
cout<<"\nRegister Number:"<<regno;
cout<<"\nName:"<<name;
cout<<"\nDepartment:"<<dept;
cout<<"\nMark 1:"<<m1;
cout<<"\nMark 2:"<<m2;
cout<<"\nMark 3:"<<m3;
cout<<"\nMark 4:"<<m4;
cout<<"\nMark 5:"<<m5;
cout<<"\nTotal:"<<total;
cout<<"\nAverage:"<<average;
cout<<"\nResult:"<<result;
}
};
int main()
{
clrscr();
result r; //Object declaration for derived class
cout<<"\n\t\t\t STUDENT INFORMATION";
r.getdata(); //Calling Base class function using derived object
r.getmarks(); //Calling Base class function using derived object
r.calculation();
r.display();
getch();
return 0;
}
OUTPUT
RESULT
Thus the concept of multiple inheritance has been implemented using C++ program.
10 d. Hierarchical Inheritance
AIM
To implement the concept of hierarchical inheritance using C++ program.
ALGORITHM
• Start the program • Invoke the base class student
• Invoke derived class ug derived from the class student • Invoke another derived class pg derived from the
same class student • Get the input data • Create object for both the class ug and pg • Call the member
functions getdata(),display() using the objects
• Display the outputs • Stop the program
SOURCE CODE
// Hierarchical Inheritance: A -> B ; A -> C
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class student //Class Declaration
{
protected:
char name[20],fathername[20],dob[10],address[20]; //Data Member Declaration
public:
void getdata() //Function to get student details
{
cout<<"\nEnter the name:";
cin>>name;
cout<<"\nEnter the father name:";
cin>>fathername;
cout<<"\nEnter the date of birth:";
cin>>dob;
cout<<"\nEnter the address:";
cin>>address;
}
void display() //Function to display student details
{
cout<<"\n\t\t\tSTUDENT DETAILS";
cout<<"\nName:"<<name;
cout<<"\nFather Name:"<<fathername;
cout<<"\nDate of Birth:"<<dob;
cout<<"\nAddress:"<<address;
}
};
class ug: public student //Deriving new class from base class
{
float x,xii;
int yearpassed;
public:
void getdata() //Function to get student details
{
student::getdata();
cout<<"\nEnter the X percentage:";
cin>>x;
cout<<"\nEnter the XII percentage:";
cin>>xii;
cout<<"\nEnter the year of XII passed:";
cin>>yearpassed;
}
void display() //Function to display student details
{
student::display();
cout<<"\nX percentage:"<<x;
cout<<"\nXII percentage:"<<xii;
cout<<"\nYear of Passed:"<<yearpassed;
}
};
class pg: public student //Deriving new class from base class
{
char ugdegree[10];
int yearpassed;
float ugpercentage;
public:
void getdata() //Function to get student details
{
student::getdata();
cout<<"\nEnter the UG degree:";
cin>>ugdegree;
cout<<"\nEnter the UG percentage:";
cin>>ugpercentage;
cout<<"\nEnter the year of passed UG:";
cin>>yearpassed;
}
void display()
{
student::display();
cout<<"\nUG Degree:"<<ugdegree;
cout<<"\nUG Percentagee:"<<ugpercentage;
cout<<"\nYear of Passed:"<<yearpassed;
}
};
int main()
{
clrscr();
ug u; //Object declaration for derived class
pg p; //Object declaration for derived class
int ch; //Variable Declaraion
do
{
cout<<"\n\t\t\t STUDENT INFORMATION";
cout<<"\n1. UG";
cout<<"\n2. PG";
cout<<"\n3. Exit";
cout<<"\n Enter your choice:";
cin>>ch;
switch(ch)
{
case 1:
u.getdata();
u.display();
break;
case 2:
p.getdata();
p.display();
break;
case 3:
exit(0);
break;
default:
cout<<"\nEnter the correct choice";
}
}while(ch<=2);
getch();
return 0;
}
OUTPUT
RESULT
Thus the concept of hierarchical inheritance has been implemented using C++ program.
10 e. Hybrid Inheritance
AIM
To implement the concept of hybrid inheritance using C++ program.
ALGORITHM
• Start the program
• Invoke the base class student
• Invoke derived class marks derived from the class student
• Invoke another base class attendance
• Invoke another derived class result derived from the class marks, class attendance
• Get the input data
• Create an object for the class result
• Call the member functions getdata(),getmarks(),getattendance(),calculation(),display() using the
object
• Display the outputs
• Stop the program
SOURCE CODE
// Hybrid Inheritance: A -> B -> C & D -> C
#include<iostream.h>
#include<conio.h>
#include<string.h>
class student //Class Declaration
{
protected:
int regno; //Data Member Declaration
char name[20],dept[5];
public:
void getdata() //Function to get student details
{
cout<<"\nEnter the register number:";
cin>>regno;
cout<<"\nEnter the name:";
cin>>name;
cout<<"\nEnter the department:";
cin>>dept;
}
};
class marks: public student //Deriving new class from another derived class
{
protected:
int m1,m2,m3,m4,m5; //Data Member Declaration
public:
void getmarks() //Function to get student marks
{
cout<<"\nEnter the mark 1:";
cin>>m1;
cout<<"\nEnter the mark 2:";
cin>>m2;
cout<<"\nEnter the mark 3:";
cin>>m3;
cout<<"\nEnter the mark 4:";
cin>>m4;
cout<<"\nEnter the mark 5:";
cin>>m5;
}
};
class attendance //Class Declaration
{
protected:
int totalhours,absent,present; //Data Member Declaration
float percentage;
public:
void getattendance() //Function to get student attendance details
{
cout<<"\nEnter the Total No. of Hours ";
cin>>totalhours;
cout<<"\nEnter the No. of Absent:";
cin>>absent;
}
};
class result: public marks,public attendance //Deriving new class from another derived class and
two base class
{
private:
int total; //Data Member Declaration
float average;
char result[6];
public:
void calculation() //Function to calculate result of the student
{
total=m1+m2+m3+m4+m5;
average=float(total)/5;
if(m1>49&&m2>49&&m3>49&&m4>49&&m5>49)
{
strcpy(result,"Pass");
}
else
{
strcpy(result,"Fail");
}
present=totalhours-absent;
percentage=float(present)/totalhours;
percentage=percentage*100;
}
void display() //Function to display student details
{
cout<<"\n\t\t\tSTUDENT DETAILS";
cout<<"\nRegister Number:"<<regno;
cout<<"\nName:"<<name;
cout<<"\nDepartment:"<<dept;
cout<<"\nMark 1:"<<m1;
cout<<"\nMark 2:"<<m2;
cout<<"\nMark 3:"<<m3;
cout<<"\nMark 4:"<<m4;
cout<<"\nMark 5:"<<m5;
cout<<"\nTotal:"<<total;
cout<<"\nAverage:"<<average;
cout<<"\nResult:"<<result;
cout<<"\nAttendance Percentage:"<<percentage;
}
};
int main()
{
clrscr();
result r; //Object declaration
cout<<"\n\t\t\t STUDENT INFORMATION";
r.getdata();
r.getmarks();
r.getattendance();
r.calculation();
r.display();
getch();
return 0;
}
OUTPUT
RESULT
Thus the concept of hybrid inheritance has been implemented using C++ program.
11 Virtual Function
AIM
To implement the concept of virtual function using C++ program.
ALGORITHM
1. Start
2. Create a Class Base with NON Virtual function and Virtual function
3. Derive new class from base class
4. In the main function declare a pointer and create objects b and d
5. Call the functions using pointer
6. Stop
SOURCE CODE
//Virtual Function
#include<iostream.h>
#include<conio.h>
class base // Base Class
{
public:
void show() //NON Virtual function
{
cout<<"base - Show \n";
}
virtual void display() //Virtual function
{
cout<<"base - display \n";
}
};
class derived: public base //Deriving new class from base class
{
public:
void show()
{
cout<<"derived - Show \n";
}
void display()
{
cout<<"derived - display \n";
}
};
int main()
{
base *ptr;
base b;
derived d;
cout<<"base object\n";
ptr=&b;
ptr->show();
ptr->display();
cout<<"Base pointer stores derived object address\n";
ptr=&d;
ptr->show();
ptr->display();
getch();
return 0;
}
OUTPUT
RESULT
Thus the concept of virtual functions has been implemented using C++ program.
12 a Biggest of two numbers either integer or float using Templates
AIM
To find the biggest of two numbers either integer or float using templates in a C++ program.
ALGORITHM
1.Start
2. Define Function Template for printing
3.Define Function Template for sorting
4. In main program , Call Function templates with integer data type
5.Calling Function template with character data type
6. Display sorted data using print
7.Stop
SOURCE CODE
#include<iostream.h>
#include<conio.h>
template<class T>
void biggest(T x,T y)
{
if(x > y)
{
cout << "Biggest value is " << x;
}
else
{
cout << "Biggest value is " << y;
}
}
void main()
{
int a,b;
float c,d;
clrscr();
cout<<"\n Enter A,B values (integer): \n";
cin>>a>>b;
biggest(a,b);
cout<<"\n\n Enter C,D values (float): \n";
cin>>c>>d;
biggest(c,d);
getch();
}
OUTPUT
RESULT
Thus the concept of templates to find biggest of two numbers either integer or float has been
implemented using C++ program.
12 b Display an array of either integers or characters using Templates
AIM
To implement the concept of templates to display array of characters or integers using C++
program.
ALGORITHM
1.Start
2. Define Function Template for printing
3.Define Function Template for sorting
4. In main program , Call Function templates with integer data type
5.Calling Function template with character data type
6. Display sorted data using print
7.Stop
SOURCE CODE
// template<class T> - Can handle all data types (int, float, double etc)
#include<iostream.h>
#include<conio.h>
template<class T> //Function Template Definition
void print(T *a,int n)
{
for(int i=0;i<n;i++)
{
cout<<a[i] << " ";
}
cout<<endl;
}
void main()
{
clrscr();
int a[]={12,11,15,13,17,14,16,19,18};
cout<<"\n Output \n";
print(a,9); //Calling Function template with integer data type
char ch[]={'b','d','a','f','h','c','e','i','g'};
cout<<"\n Output \n";
print(ch,9); //Calling Function template with character data type
getch();
}
OUTPUT
RESULT
Thus the concept of templates to display array of characters or integers has been implemented
using C++ program.
12 c Display a sorted array of integers and characters using Templates
AIM
To implement the concept of templates to display a sorted array of integers or characters using
C++ program
ALGORITHM
1.Start
2. Define Function Template for printing
3.Define Function Template for sorting
4. In main program , Call Function templates with integer data type
5.Calling Function template with character data type
6. Display sorted data using print
7.Stop
SOURCE CODE
// template<class T> - Can handle all data types (int, float, double etc)
#include<iostream.h>
#include<conio.h>
template<class T> //Function Template Definition
void print(T *a,int n)
{
for(int i=0;i<n;i++)
{
cout<<a[i] << " ";
}
cout<<endl;
}
template<class T> //Function Template Definition
void sort(T *a,int n)
{
for(int i=1;i<n;i++)
{
T value=a[i];
int j=i;
while(value < a[j-1] && j > 0)
{
a[j]=a[j-1];
j=j-1;
}
a[j]=value;
}
}
void main()
{
clrscr();
int a[]={12,11,15,13,17,14,16,19,18};
cout<<"\n Before Sorting\n";
print(a,9); //Calling Function template with integer data type
sort(a,9); //Calling Function template with integer data type
cout<<"\n After sorting\n";
print(a,9);
char ch[]={'b','d','a','f','h','c','e','i','g'};
cout<<"\n Before Sorting\n";
print(ch,9); //Calling Function template with character data type
sort(ch,9); //Calling Function template with character data type
cout<<"\n After sorting\n";
print(ch,9);
getch();
}
OUTPUT
RESULT
Thus the concept of templates to display a sorted array of integers or characters has been
implemented using C++ program.
13 Exception Handling
AIM
To implement the concept of exception handling using C++ program
ALGORITHM
1. Start
2. Declare the variables a, b, d
3. Initialize a=4 and b=2
4. In try block if b=0 , then throw b
5. Compute and print d= a/b
6. In catch block show the error message
SOURCE CODE
// try block - error handling block
// throw - skips code in try block and run catch block
// catch - Show error message
#include<iostream>
int main()
{
int a,b; // Variable Declaration
float d;
a = 4;
b = 0;
try // Try block
{
if(b==0)
{
throw(b); // Throw Statement
}
d=a/b;
std::cout<<"The value of d is :"<<d<<"\n";
}
catch(int i) //Catch block
{
std::cout<<"Answer is infinite because b is " << i<<"\n";
}
//getch();
return 0;
}
OUTPUT
RESULT
Thus the concept of exception handling has been implemented using C++ program.

Potrebbero piacerti anche