Lab Manual

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 115
At a glance
Powered by AI
The document discusses various C programs to solve problems like solving quadratic equations, finding student grades, performing searches etc. using conditional and control statements.

The steps include declaring variables, reading coefficients, finding the determinant, checking if it is greater/equal/less than 0, and calculating the roots based on the condition.

The steps include declaring a variable to store mark, reading the mark as input, checking if it is in different ranges to determine the grade and printing the grade.

Ex.

No: 1
Date : C Programs using Conditional & Control Statements

C Programs using Conditional Statements

1.1. Write a C program to solve Quadratic Equations

AIM:

To write a C program to solve quadratic equations.

ALGORITHM

Step 1:Start
Step 2:Declare variables a,b,c,d,root1,root2
Step 3:Read the coefficients and constants : a, b and c respectively.
Step 4:Find determinant, d= (b*b)-(4*a*c).
Step 5:If d is greater than 0 then
5.1) Print the roots are real and distinct.
5.2) Find the root r1=((-b+ pow(d,0.5))/2*a)
5.3) Find the root r2=((-b- pow(d,0.5))/2*a)
5.4) Print the roots r1 and r2.
Step 6: Else
6.1) If d is equal to 0 then
a) Print the real and equal.
b) Find the roots r1=r2=(-b/(2*a))
c) Print the roots r1 and r2.
6.2) Else
a) Assign d=-d
b) Print the roots are imaginary.
c) Find m=(-b/(2*a))
d) Find s=(pow(d,.5)/(2*a))
e) Print the roots m+is and m-is.
6.3)End if.
Step 7:End if.
Step 8:Stop.

1
PROGRAM

#include<stdio.h>
#include<math.h>
int main()
{
float a,b,c;
float d,root1,root2;
printf("Enter a, b and c of quadratic equation:");
scanf("%f%f%f",&a,&b,&c);
d = b * b - 4 * a * c;
if(d < 0){
printf("Roots are complex number.\n");
printf("Roots of quadratic equation are: ");
printf("%.3f%+.3fi",-b/(2*a),sqrt(-d)/(2*a));
printf(", %.3f%+.3fi",-b/(2*a),-sqrt(-d)/(2*a));
return 0;
}
else if(d==0)
{
printf("Both roots are equal.\n");
root1 = -b /(2* a);
printf("Root of quadratic equation is: %.3f ",root1);
return 0;
}
else
{
printf("Roots are real numbers.\n");
root1 = ( -b + sqrt(d)) / (2* a);
root2 = ( -b - sqrt(d)) / (2* a);
printf("Roots of quadratic equation are: %.3f , %.3f",root1,root2);
}
return 0;
}

2
OUTPUT:

Enter a, b and c of quadratic equation: 2 4 1


Roots are real numbers.
Roots of quadratic equation are: -0.293, -1.707

3
RESULT:

Thus the C program to solve quadratic equations was executed successfully and the output was verified.

4
1.2. Write a C program to display the Grade of Students

AIM:

To write a C program to display the grade of students.

ALGORITHM

Step 1:Start
Step 2:Declare variable num.
Step 3:Input students mark
Step 4: if grade < 100 AND grade > 75 { student got an A }

else if grade < 75 AND grade > 60 { student got a B }

else if grade < 60 AND grade > 50 { student got a C }

else if grade < 50 AND grade > 40 { student got a D }

else { student got an F } // didn't fit into any of the above scenarios, so must be an F

Step 5: Print to screen what the student got

5
PROGRAM

#include <stdio.h>
void main()
{
int num;
printf("Enter your mark ");
scanf("%d",&num);
printf(" You entered %d Marks", num);
if(num >= 80)
printf(" You got A grade");
else if ( num >=60)
printf(" You got B grade");
else if ( num >=40)
printf(" You got C grade");
else
printf(" You Failed in this exam");
}

6
OUTPUT:

1. Enter Your Mark:

90

You entered 90 Marks.

You got A grade.

2. Enter Your Mark:

30

You entered 30 Marks.

You Failed in this exam

7
RESULT:

Thus the C program to display the grade of students was executed successfully and the output was verified.

8
C Programs using Control Statements

1.3. Write a C program to find out the Largest Digit

AIM:

To write a C program to find out the largest digit.

ALGORITHM:

Step 1:Start
Step 2:Declare variable num.
Step 3:Input Number.
Step 4: Divide the given number by 10 and find the remainder value.
Step 5: Store the remainder value at another variable, d.
Step 6: If bigdig<d, then bigdig=d.
Step 7: Then divide the given number by 10.
Step 8: Print the largest digit among the given number.

9
PROGRAM

#include<stdio.h>
#include<conio.h>
void main()
{
int num,bigdig=0,d;
clrscr();
printf("\nEnter the number:");
scanf("%d",&num);
while(num>0)
{
d=num%10;
if(bigdig<d)
bigdig=d;
num=num/10;
}
printf("\nLargest Digit is %d",bigdig);
getch();
}

10
OUTPUT:

Enter the number:

897

Largest Digit is 9.

11
RESULT:

Thus the C program to find the largest digit was executed successfully and the output was verified.

12
Ex.No: 2
Date C Programs using Arrays, Strings and Pointers and Functions

C Programs using Arrays

2.1. Write a C program to find Maximum and minimum number among the given numbers

AIM:

To write a C program to find maximum and minimum number among the given numbers.

ALGORITHM:

Step1 : Start

Step 2: Declare a variable number to enter the array elements

Step 3: Initialize min = 1000 & max =0.

Step 4: Check if min<a[i]

Step 5: Store a[i] as min value.

Step 6: Check if max>a[i]

Step 7: Store a[i] as max value.

Step 8: Then declare min as minimum number & max as maximum number.

Step 9: Print the minimum number and maximum number.

13
PROGRAM

#include<stdio.h>
#include<conio.h>
void main()
{
int i,a[20],min=1000,n,max=0;
clrscr();
printf("\nHow many array elements you want to enter!");
scanf("%d",&n);
printf("\nEnter array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(min>a[i])
min=a[i];
if(max<a[i])
max=a[i];
}
printf("\nLinear Search Techniques");
printf("\nMinimum number:%d Maximum number:%d",min,max);
getch();
}

14
OUTPUT:

How many array elements you want to enter!"); 3

Enter array elements:23,34,45

Minimum number:23 Maximum number:45

15
RESULT:

Thus the C program to find the maximum and minimum number among the given numbers was executed
successfully and the output was verified.

16
2.2. Write a C program to display the Sum of array element and Reverse the same

AIM:

To write a C program to display the sum of array element and reverse the same.

ALGORITHM:

Step 1: Start

Step2: Initialize variable.

Step 3: Get the count for array elements.

Step 4: Add the given array elements and store it in sum variable.

Step 5: Also reverse the array elements.

Step 6: Print the addition of array elements & reverse of array elements.

17
PROGRAM

#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],i,N,sum=0;
clrscr();
printf("Enter number of numbers in array:");
scanf("%d",&N);
printf("\nEnter array elements:");
for(i=0;i<N;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
printf("\Reverse of array content:");
for(i=N-1;i>=0;i--)
printf("\n%d",a[i]);
printf("\nSum of the array elements:%d",sum);
getch();
}

18
OUTPUT:

Enter number of numbers in array:2


Enter array elements:23
56
Reverse of array content:
56
23
Sum of the array elements:79

19
RESULT:

Thus the C program to display the sum of array elements and reverse the same was executed successfully
and the output was verified.
20
C Programs using Strings

2.3. Write a C program that, String Manipulation using String inbuilt function

AIM:

To write a C program to implement string manipulation using string inbuilt functions

ALGORITHM:

Step1: Start

Step 2: Enter two strings

Step 3: Use strlen() method to find the length of the string.

Step 4: Print the length of two strings.

Step 5: Use strcat() method to concatenate two strings.

Step 6: Use strcmp() method to compare two strings.

Step 7: Use strrev() method to reverse the strings.

Step 8: Use strupr() method to get the upper case of strings.

Step 9: Use strlwr() method to get the lower case of strings.

Step 10: Print all the results.

21
PROGRAM

#include <stdio.h>
#include <string.h>
#include<conio.h>
void main()
{
char str1[20],str2[10],str3[30];
int len,cmp;
clrscr();
printf("\nEnter 2 strings");
scanf("%s %s",str1,str2);
len=strlen(str1);
printf("\nLength of %s is %d\t",str1,len);
strcat(str1,str2);
printf("\nConcatenated string is %s",str1);
cmp=strcmp(str1,str2);
if(cmp>0)
printf("\n%s > %s",str1,str2);
else
{
if(cmp<0)
printf("\n%s < %s",str1,str2);
else
printf("\n%s = %s",str1,str2);
}
strrev(str2);
printf("\nReverse string is %s",str2);
strupr(str1);
printf("\n%s is in upper case",str1);
strlwr(str1);
printf("\n%s is in lower case",str1);
getch();
}

22
OUTPUT:

Enter 2 strings
Welcome
Hindusthan

Length of Welcome is 7
Concatenated string is WelcomeHindusthan
WelcomeHindusthan > Hindusthan
Reverse string is nahtsudniH
WELCOMEHINDUSTHAN is in upper case
welcomehindusthan is in lower case

23
RESULT:

Thus the C program to implement string manipulation using string inbuilt functions were executed
successfully and the output was verified.

24
C Programs using Pointers and Structures

2.4. Write a C Program to display, Student Details using pointers and structures

AIM:

To write a C program to display student details using pointers and structures

ALGORITHM:

Step 1: Start

Step 2: Create the structure for student

Step 3: Get student name, rollno and 3 marks

Step 4: Store all the values using pointers.

Step 5: Find the total value of 3 marks for each student.

Step 5: Display the student record: name, rollno and 3 marks.

25
PROGRAM

#include<conio.h>
#include<string.h>
#include<stdio.h>
struct student
{
char name[10];
int rn;
int m1,m2,m3;
int total;
};
void main()
{
struct student *s;
int n,i;
clrscr();
printf("enter the number of student ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nenter the student %d record\n",i+1);
printf("\nenter name:");
scanf("%s",(s+i)->name);
printf("\nenter roll no:");
scanf("%d",&(s+i)->rn);
printf("\nenter 3 marks:");
scanf("%d%d%d",&(s+i)->m1,&(s+i)->m2,&(s+i)->m3);
(s+i)->total=(s+i)->m1+(s+i)->m2+(s+i)->m3;
}
for(i=0;i<n;i++)
{
printf("\nThe student %d record is\n",i+1);
printf("\nName:%s",(s+i)->name);
printf("\nRoll no:%d",(s+i)->rn);
printf("\n3 marks:%d %d %d",(s+i)->m1,(s+i)->m2,(s+i)->m3);
printf("\nTotal mark:%d",(s+i)->total);
}
getch();
}

OUTPUT:

26
Enter the number of student 3
Enter the student 1 record
Enter name:Minu
Enter roll no:101
Enter 3 marks:90
67
80

Enter the student 2 record


Enter name:Sruthi
Enter roll no:102
enter 3 marks:90
98
99

Enter the student 3 record


Enter name:Mayura
Enter roll no:103
Enter 3 marks:96
75
89

The student 1 record is


Name:Minu
Roll no:101
3 marks:90 67 80
Total mark:237

The student 2 record is


Name:Sruthi
Roll no:102
3 marks:90 98 99
Total mark:287

The student 3 record is


Name:Mayura
Roll no:103
3 marks:96 75 89
Total mark:260

27
RESULT:

Thus the C program to display the students details using pointers and structures were executed successfully
and the output was verified.

28
C programs using Functions

2.5. Write a C Program to find the Factorial of a given number.

AIM:

To write a C program to find the factorial of given number.

ALGORITHM:

Step 1: Start

Step 2: Initialize the variable

Step 3: Write the function fact().

Step 4: If n=0 then factorial is 1.

Step 5: Else, Use the formula n*fact(n-1).

Step 6: Print the factorial value using fact() method.

29
PROGRAM:

#include<stdio.h>
#include<conio.h>
int fact(int n)
{
int f;
if(n==0)
return 1;
else
{
f=n*fact(n-1);
return(f);
}
}
void main()
{
int n;
clrscr();
printf("\nEnter a number:");
scanf("%d",&n);
printf("\nFactorial value is %d",fact(n));
getch();
}

30
OUTPUT:

Enter a number:7

Factorial value is 5040

31
RESULT:

Thus the C program to find the factorial of given number was executed successfully and the output was
verified.

32
2.6. Write a C Program to work with Calculator

AIM:

To write a C program to work with calculator

ALGORITHM:

Step 1: Start

Step 2: Write add(), sub(),mul(),div(),mod() methods for two variables.

Step 3: By using switch case, select the operations in calculator.

Step 4: call add(), sub(),mul(),div(),mod() methods for corresponding selections.

Step 5: Print the output.

33
PROGRAM:

#include<stdio.h>
#include<conio.h>
int add(int a,int b)
{
return(a+b);
}
int sub(int a,int b)
{
return(a-b);
}
int mul(int a,int b)
{
return(a*b);
}
int div(int a,int b)
{
return(a/b);
}
int mod(int a,int b)
{
return(a%b);
}
void main()
{
int a,b,ch;
clrscr();
printf("\nEnter two numbers:");
scanf("%d%d",&a,&b);
printf("\nPossible operations in calculator");
printf("\n1.+\n2.-\n3.*\n4./\n5.%");
printf("\nChoice the option:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nAddition:%d",add(a,b));
break;
case 2:
printf("\nSubtraction:%d",sub(a,b));
break;
case 3:
printf("\nMultiplication:%d",mul(a,b));
break;
case 4:
34
printf("\nDivision:%d",div(a,b));
break;
case 5:
printf("\nModulus:%d",mod(a,b));
break;
default:
printf("\nInvalid option");
}
getch();
}

35
OUTPUT:

Enter two numbers:34


58

1. Possible operations in calculator


1.+
2.-
3.*
4./
5.%
Choice the option:1

Addition:92

Enter two numbers:34


3

Possible operations in calculator


1.+
2.-
3.*
4./
5.%
Choice the option:4

Division:11

Enter two numbers:45


4

Possible operations in calculator


1.+
2.-
3.*
4./
5.%
Choice the option:5

Modulus:1

36
RESULT:

Thus the C program to work with calculator was executed successfully and the output was verified.
37
Ex.No: 3
Date LINKED LIST IMPLEMENTATION

AIM:

To write a C program to implement singly linked list.

ALGORITHM:

1. Start the program.


2. Get the choice from the user.
3. If the choice is insert, get the data from the user and add them to the list.
4. If the choice is display, the items in the list are displayed to the user.
5. If the choice is size, the number of items in the list are displayed.
6. If the choice is delete, get the data to be deleted and delete it from the list.
7. Terminate the program.

38
PROGRAM:

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

struct node
{
int data;
struct node *next;
}*head;

void append(int num)


{
struct node *temp,*right;
temp= (struct node *)malloc(sizeof(struct node));
temp->data=num;
right=(struct node *)head;
while(right->next != NULL)
right=right->next;
right->next =temp;
right=temp;
right->next=NULL;
}

void add( int num )


{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->data=num;
if (head== NULL)
{
head=temp;
head->next=NULL;
}
else
{
temp->next=head;
head=temp;
}
}

void insert(int num)


{
int c=0;
struct node *temp;
temp=head;
if(temp==NULL)
{
add(num);
}

39
else
{
while(temp!=NULL)
{
if(temp->data<num)
c++;
temp=temp->next;
}
if(c==0)
add(num);
else
append(num);
}
}

int delete(int num)


{
struct node *temp, *prev;
temp=head;
while(temp!=NULL)
{
if(temp->data==num)
{
if(temp==head)
{
head=temp->next;
free(temp);
return 1;
}
else
{
prev->next=temp->next;
free(temp);
return 1;
}
}
else
{
prev=temp;
temp= temp->next;
}
}
return 0;
}

void display(struct node *r)


{
r=head;
if(r==NULL)
{
return;
}

40
while(r!=NULL)
{
printf("%d ",r->data);
r=r->next;
}
printf("\n");
}

int count()
{
struct node *n;
int c=0;
n=head;
while(n!=NULL)
{
n=n->next;
c++;
}
return c;
}

int main()
{
int i,num;
struct node *n;
head=NULL;
while(1)
{
printf("\nList Operations\n");
printf("===============\n");
printf("1.Insert\n");
printf("2.Display\n");
printf("3.Size\n");
printf("4.Delete\n");
printf("5.Exit\n");
printf("Enter your choice : ");
if(scanf("%d",&i)<=0)
{
printf("Enter only an Integer\n");
exit(0);
}
else
{
switch(i)
{
case 1:printf("Enter the number to insert : ");
scanf("%d",&num);
insert(num);
break;
case 2: if(head==NULL)
{
printf("List is Empty\n");

41
}
else
{
printf("Element(s) in the list are : ");
}
display(n);
break;
case 3: printf("Size of the list is %d\n",count());
break;
case 4: if(head==NULL)
printf("List is Empty\n");
else
{
printf("Enter the number to delete : ");
scanf("%d",&num);
if(delete(num))
printf("%d deleted successfully\n",num);
else
printf("%d not found in the list\n",num);
}
break;
case 5: return 0;

default: printf("Invalid option\n");


}
}
}
}

42
OUTPUT:

List Operations
============
1.Insert
2.Display
3.Size
4.Delete
5.Exit
Enter your choice: 1
Enter the number to insert: 10

List Operations
============
1.Insert
2.Display
3.Size
4.Delete
5.Exit
Enter your choice: 1
Enter the number to insert: 20

List Operations
============
1.Insert
2.Display
3.Size
4.Delete
5.Exit
Enter your choice: 1
Enter the number to insert: 30

List Operations
============
1.Insert
2.Display
3.Size
4.Delete
5.Exit
Enter your choice: 2
Element(s) in the list are: 10 20 30

List Operations
============
1.Insert
2.Display
3.Size
4.Delete

43
5.Exit
Enter your choice: 3
Size of the list is 3

List Operations
============
1.Insert
2.Display
3.Size
4.Delete
5.Exit
Enter your choice: 4
Enter the number to delete : 20
20 deleted successfully

List Operations
============
1.Insert
2.Display
3.Size
4.Delete
5.Exit
Enter your choice: 5

44
RESULT:

Thus the C program to implement singly linked list was executed successfully and the output was verified.

45
Ex.No: 4
Date FILE HANDLING IN C

4.1. Write a program to write data to file and display the contents of the file

AIM:

To write a C program to implement file handling.

ALGORITHM:

Step1: Define the file pointer

Step2: Open the file student.txt in write mode

Step3: Check the file status, if error display error message

Step4: Write the student details to the file

Step5: Read the file student.txt file contents until EOF.

Step 6: Print the details on the console output (Monitor).

Step7: Close the file.

Step 8: Stop.

46
PROGRAM:

#include<stdio.h>

#include<stdlib.h>

#include<conio.h>

void main()

FILE *fp;

char str[20];

int num;

clrscr();

fp=fopen("student.txt","w+");

if(fp==NULL){

printf("File opening Error");

exit(0);}

fprintf(fp,"%s\t%d\n","Meenu",1000);

fprintf(fp,"%s\t%d\n","Neethu",2000);

fprintf(fp,"%s\t%d\n","Sachu",3000);

fprintf(fp,"%s\t%d\n","Muthu",4000);

rewind(fp);

while(!feof(fp)){

fscanf(fp,"%s%d",str,&num);

printf("%s\t%d\n",str,num);

fclose(fp);

getch();}
47
OUTPUT:

Meenu 1000

Neethu 2000

Sachu 3000

Muthu 4000

Muthu 4000

48
RESULT:

Thus the C program to write data to file and display the content of the file was executed successfully and the
output was verified.

49
4.2 Write a program to write employee data to the file from console input and display the
contents of the file.

AIM:

To write a C program to write employee data to the file from console input and display the contents of the
file.

ALGORITHM:

Step1: Define the file pointer

Step2: Open the file employee.in in wb mode

Step3: Check the file status, if error display error message

Step4: Read an employee details from the input

Step 5: Write the employee details to the file

Step 6: Close the file

Step 7: Open the file employee.in rbmode

Step 8: Check the file status, if error display error message.

Step 9: Read the file employee.in file contents until EOF.

Step 10: Print the details on the console output (Monitor).

Step 11: Close the file.

Step 12 : Stop.

50
PROGRAM:

#include<stdio.h>

#include<ctype.h>

#include<stdlib.h>

#include<conio.h>

struct employee

char name[20];

float sal;

};

main()

FILE *fp;

struct employee e;

int i;

if((fp=fopen("employee.in","wb"))==NULL)

printf("Error Opening File");

exit(0);

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

printf("\nEnter the name and salary:");

scanf("%s%f",e.name,&e.sal);

fwrite(&e,sizeof(e),1,fp);
51
}

fclose(fp);

fp=fopen("employee.in","rb");

if(fp==NULL)

fprintf(stderr,"Error Opening File");

exit(0);

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

fread(&e,sizeof(e),1,fp);

printf("\n Name=%s salary=%f",e.name,e.sal);

fclose(fp);

getch();

52
OUTPUT:

Enter the name and salary:Mini 30000

Enter the name and salary:Niju 45000

Enter the name and salary:jiji 76000

Enter the name and salary:Meenu 43000

Name=Mini salary=30000.000000
Name=Niju salary=45000.000000
Name=jiji salary=76000.000000
Name=Meenu salary=43000.000000

53
RESULT:

Thus the C program to write employee data to the file from console input and display the contents of the file
was executed successfully and the output was verified.

54
4.3. SEQUENTIAL ACCESS

AIM:

To write a C program to implement sequential access.

ALGORITHM:

Step1: Define the structure with student details

Step 2: Define the file pointer

Step 3: Open the file student.dat in write mode

Step 4: Read n

Step 5: Read n student details

Step 6: Write the student details to the file

Step7: Close the file.

Step 8: Open the file in Read mode

Step 9: Display Menu

Step 10: Read Option

Step 11:If Option =1, print student details from the file

Step 12: If Option = 2, search the student details in the file using the key

Step 13: If Option =3, exit

Step 14: Close the file

Step 15: Stop.

55
PROGRAM:

#include<stdio.h>

#include<conio.h>

typedef struct

int sno;

char name[25];

int m1,m2,m3;

STD;

STD s;

void display(FILE *);

int search(FILE *,int);

void main()

int i,n,sno_key,opn;

FILE *fp;

clrscr();

printf("How many records:");

scanf("%d",&n);

fp=fopen("stud.dat","w");

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

printf("Enter the student info:%d(Sno,Name,M1,M2,M3):",i+1);

scanf("%d%s%d%d%d",&s.sno,s.name,&s.m1,&s.m2,&s.m3);

fwrite(&s,sizeof(s),1,fp);

}
56
fclose(fp);

fp=fopen("stud.dat","r");

do

printf("1-Display\n 2-Search\n 3-Exit \n Your Option?");

scanf("%d",&opn);

switch(opn)

case 1: printf("\n Student Records in the File\n");

display(fp);

break;

case 2:printf("Read SNO of the student to be searched?");

scanf("%d",&sno_key);

if(search(fp,sno_key))

printf("success! Record found in the file\n");

printf("%d\t%s\t%d\t%d\t%d\n",s.sno,s.name,s.m1,s.m2,s.m3);

else

printf("Failure!! Record with USN %d not found\n",sno_key);

break;

case 3:printf("Exit!! press a key...");

getch();

break;

default:printf("Invalid option!!! Try again!!!\n");

break;

while(opn!=3);
57
fclose(fp);

void display(FILE *fp)

rewind(fp);

while(fread(&s,sizeof(s),1,fp))

printf("%d\t%s\t%d\t%d\t%d\n",s.sno,s.name,s.m1,s.m2,s.m3);

int search(FILE *fp,int sno_key)

rewind(fp);

while(fread(&s,sizeof(s),1,fp))

if(s.sno==sno_key)

return 1;

return 0;

58
OUTPUT:

How many records:2

Enter the student info:1(Sno,Name,M1,M2,M3):1 Sruthi 80 90 100

Enter the student info:2(Sno,Name,M1,M2,M3):2 Mayura 90 90 80

1-Display

2-Search

3-Exit

Your Option?1

Student Records in the File

1 Sruthi 80 90 100

2 Mayura 90 90 80

1-Display

2-Search

3-Exit

Your Option?2

Read SNO of the student to be searched?1

success! Record found in the file

1 Sruthi 80 90 100

1-Display

2-Search

3-Exit

Your Option?3

Exit!! press a key...


59
RESULT:

Thus the C program to implement sequential access of file was executed successfully and the output was
verified.

60
4.4. RANDOM ACCESS

AIM:

To write a C program to implement random access.

ALGORITHM:

Step1: Define the structure with employee details

Step 2: Define the file pointer

Step 3: Open the file People.txt in write mode

Step 4: Read n

Step 5: Read n employee details

Step 6: Write the employee details to the file

Step7: Close the file.

Step 8: Open the file in w+b mode

Step 9: Read record to search from the file

Step 10: If found display the employee details from the file

Step 11:If not found display the appropriate message

Step 12: Close the file

Step 13 : Stop.

61
PROGRAM:

#include<stdio.h>

#include<string.h>

#include<conio.h>

struct record

char empname[20];

int age;

float salary;

};

typedef struct record person;

FILE *people;

void main()

person employee;

int i,n;

int rec,result;

FILE *fp;

clrscr();

printf("How many Records?");

scanf("%d",&n);

fp=fopen("PEOPLE.txt","w");

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

printf("Enter the employee info:%d(EmpName,Age,Salary):",i+1);


62
scanf("%s%d%f",employee.empname,&employee.age,&employee.salary);

fwrite(&employee,sizeof(employee),1,fp);

fclose(fp);

//int rec;

//int result;

people=fopen("PEOPLE.txt","r+b");

printf("Which record do you want to read from file (-999 to Stop)?");

scanf("%d",&rec);

while(rec>=0)

fseek(people,rec*sizeof(employee),SEEK_SET);

result=fread(&employee,sizeof(employee),1,people);

if(result==1)

printf("\nRECORD%d\n",rec);

printf("Given name...:%s\n",employee.empname);

printf("Age...:%dyears \n",employee.age);

printf("Current Salary:$%8.2f\n\n",employee.salary);

else

printf("\nRecord %d not found!\n\n",rec);

printf("Which record do you want [0-3]?");

scanf("%d",&rec);

fclose(people);

63
OUTPUT:

How many Records?2

Enter the employee info:1(EmpName,Age,Salary):Nijan 30 25000

Enter the employee info:2(EmpName,Age,Salary):Jeeva 23 20000

Which record do you want to read from file (-999 to Stop)?1

RECORD1

Given name...:Jeeva

Age...:23years

Current Salary:$20000.00

64
RESULT:

Thus the C program to implement random access of file was executed successfully and the output was
verified.

65
Ex.No: 5
Date STACKS AND QUEUES

5.1. Linked stack implementation-operations on a stack

AIM:

To write a C program for linked list implementation of stack and its operations.

ALGORITHM:

Step 1: Start
Step 2: Initialize the variable
Step 3: Write methods for push, pop, display and exit.
Step 4: Create the structure for node.
Step 5: Push() : Assign the data value and link value for temporary variable & store the temporary
variable as top element.
Step 6: Pop(): Check whether the stack is empty or not
Store the top value in temporary variable.
Delete the data value of temporary variable.
Then by using free() function, free temporary variable.
Finally assign the address part of the top, as top element.
Step 7: Display(): Check whether the stack is empty or not.
Display the contents of the stack.

66
PROGRAM:

#include<stdio.h>
void push();
void pop();
void display();
main()
{
int n;
printf("\tMENU\n1.PUSH\n2.POP \n3.DISPLAY\n4.EXIT\n");
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Invalid choice\n");
break;
}
}
while(n!=4);
}

typedef struct node


{
int data;
struct node *link;
}n;
n *top=NULL;

void push()

67
{
int item;
n *temp;
printf("Enter the item\n");
scanf("%d",&item);
temp=(n*)malloc(sizeof(n));
temp->data=item;
temp->link=top;
top=temp;
}

void pop()
{
n *temp;
if(top==NULL)
printf("Stack is empty\n");
else
{
temp=top;
printf("The element deleted = %d

\n",temp->data);
free(temp);
top=top->link;
}
}

void display()
{
n *save;
if(top==NULL)
printf("Stack is empty\n");
else
{
save=top;
printf("The elements of the stack are :");
while(save!=NULL)
{
printf("%d\t",save->data);
save=save->link;
}
printf("\nTopmost element = %d

\n",top->data); } }

68
OUTPUT:

MENU
1.PUSH
2.POP
3.DISPLAY
4.EXIT

Enter your choice


1
Enter the item
15

Enter your choice


1
Enter the item
25

Enter your choice


1
Enter the item
35

Enter your choice


3
The elements of the stack are :35 25 15
Topmost element = 35

Enter your choice


2
The element deleted = 35

Enter your choice


3
The elements of the stack are :25 15
Topmost element = 25

Enter your choice 4


Exit

69
RESULT:

Thus the C program for linked list implementation of stack and its operations was executed successfully
and output was verified.

70
5.2. INFIX TO POSTFIX

AIM:

Write a C program for conversion of infix to postfix expression.

ALGORITHM:

Step 1: Start
Step 2: Initialize the variable
Step 3: Define the structure for node.
Step 4: Set the priority values for all the operators in stack operator.
Step 5: Set the priority values for all the operators in input operator.
Step 6: Get the infix expression.
Step 7: Using the priority values & Stack Concepts, convert the infix expression into postfix
expression.
Step 8: Print the postfix expression.

71
PROGRAM:

#include<stdio.h>
#include<ctype.h>
#include<string.h>
#define max 9
typedef struct node
{
char data;
struct node *next;
}stack;
int push(char);
int pop(char *);
stack *getnode( );
void releasenode(stack *);
void intopost(char[],char[]);
int priority(char p[][2],char data);
stack *tos=NULL;
char ip[max][2]={{'(',max},{')',0},{'\0',0},{'+',1},{'-',1},{'*',2},{'/',2},{'%',2},{'^',3}};
char sp[max][2]={{'(',0},{')',-1},{'\0',0},{'+',1},{'-',1},{'*',2},{'/',2},{'%',2},{'^',3}};
void main( )
{
char instr[20],poststr[20];
clrscr( );
printf("Enter the infix expression:\n");
scanf("%s",instr);
intopost(instr,poststr);
printf("The postfix expression is:%s",poststr);
getch( );
}
stack *getnode( )
{
return((stack *)malloc(sizeof(stack)));
}
void releasenode(stack *newnode)
{
free(newnode);
}
int push(char value)
{
extern stack *tos;
stack *newptr;
newptr=getnode( );
if(newptr==NULL)
return -1;
newptr->data=value;
newptr->next=tos;

72
tos=newptr;
return 0;
}
int pop(char *value)
{
extern stack *tos;
stack *temp;
if(tos==NULL)
return -1;
temp=tos;
tos=tos->next;
*value=temp->data;
releasenode(temp);
return 0;
}
void intopost(char instr[],char poststr[])
{
char ch,item;
int i=0,st=0,spr,ipr;
push('\0');
while((ch=instr[st++])!=NULL)
{
if(tolower(ch)>='a'&&tolower(ch)<='z')
poststr[i++]=ch;
else if(ch=='(')
push(ch);
else if(ch==')')
{
pop(&item);
while(item!='(')
{
poststr[i++]=item;
pop(&item);
}
}
else
{
pop(&item);
spr=priority(sp,item);
ipr=priority(ip,ch);
while(sp[spr][1]>=ip[ipr][1])
{
poststr[i++]=item;
pop(&item);
spr=priority(sp,item);
}push(item);
push(ch);
}
}
while(!pop(&item))
poststr[i++]=item;
}
int priority(char p[][2],char data)

73
{
int ind;
for(ind=0;ind<max;ind++)
if(p[ind][0]==data)
return ind;
}

74
OUTPUT:

Enter the infix expression: a-b*c+d/g

The postfix expression is: abc*-dg/+

75
RESULT:

Thus the C program for infix to postfix conversion was executed successfully and output was
verified.

76
5. 3. PROGRAM FOR EVALUATION OF POSTFIX EXPRESSION

AIM:

Write a C program for evaluation of postfix expression

ALGORITHM:

Step 1: Start
Step 2: Read the token.
Step 3: if the token is an operator:
i) pop the top two elements of the stack.
ii) perform the operation on the elements.
iii) push the result of the operation onto the stack.
Step 4: else
(i) push the token (which must be a number)onto the stack
Step 5: Print the result

77
PROGRAM:

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define size 80
/*declaration of stack data structure*/
struct stack
{
double s[size];
int top;
}st;
void main()
{
char exp[size];
int len;
double result;
double post();
clrscr();
printf("enter the postfix expression\n");
scanf("%s",exp);
len=strlen(exp);
exp[len]='$';/*append $ at the end as a endmarker*/
result=post(exp);
printf("the value of the expression is %f\n",result);
getch();
exit(0);
}
double post(char exp[])
{
char ch,*type;
double result,val,op1,op2;
void push(double);
double pop();
int i;
st.top=0;
i=0;
ch=exp[i];
while(ch!='$')
{
if(ch>='0' && ch<='9')
type="operand";
else if(ch=='+'||ch=='-'|| ch=='*'||ch=='/'||ch=='^')
type="operator";
if(strcmp(type,"operand")==0)
{
val=ch-48;
push(val);
78
}
else
if(strcmp(type, "operator")==0)
{
op2=pop();
op1=pop();
switch(ch)
{
case '+':
result=op1+op2;
break;
case '-':
result=op1-op2;
break;

case '*':
result=op1*op2;
break;

case '/':
result=op1/op2;
break;
case '^':
result=pow(op1,op2);
break;
}
push(result);
}
i++;
ch=exp[i];
}
result=pop();
return(result);
}
void push(double val)
{
if(st.top+1>=size)
printf("\nstack is full\n");
st.top++;
st.s[st.top]=val;
}
double pop()
{
double val;
if(st.top==-1)
printf("\nstack is empty\n");
val=st.s[st.top];
st.top--;
return(val);
}

79
OUTPUT:

Enter the postfix expression

12+34*+

The value of the expression is 15.000000

80
RESULT:

Thus the C program for evaluating postfix expression was executed successfully and output was
verified.

81
4. LINKED QUEUE IMPLEMENTATION-OPERATIONS ON A QUEUE

AIM:

To write a C program for linked implementation for Queue and its operations.

ALGORITHM:

Step 1: Start
Step 2: Create a structure for node.
Step 3: Write the functions for enqueue, dequeue, display, create.
Step 4: enqueue():
If rear part is null
Create a memory space for rear
rear->ptr=null
Set data part as arear->info part
Set rear part as front.
Else
Create a memory space for temparory variable
Set temp as rear->ptr
Set data as temp->info
Set temp->ptr as null
Rear=temp.
Increase the count.

Step5: dequeue():

Check whether the queue is empty or not.


If not,
Store the front part in temporary variable
Then free the front part.
Else
Set front=null
Rear =null

Step 6: Print the output

82
PROGRAM:

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

struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;

int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();

int count = 0;

void main()
{
int no, ch, e;

printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);

83
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element :%d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}

/* Create an empty queue */


void create()
{
front = rear = NULL;
}

/* Returns queue size */


void queuesize()
{
printf("\n Queue size : %d", count);
}

/* Enqueing the queue */


void enq(int data)
{
if (rear == NULL)

84
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
}
count++;
}

/* Displaying the queue elements */


void display()
{
front1 = front;
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}

/* Dequeing the queue */


void deq()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)

85
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}

/* Returns the front element of queue */


int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}

/* Display if queue is empty or not */


void empty()
{
if ((front == NULL) && (rear== NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}

86
OUTPUT:

1 - Enque

2 - Deque

3 - Front element

4 - Empty

5 - Exit

6 - Display

7 - Queue size

Enter choice : 1

Enter data : 15

Enter choice : 1

Enter data : 25

Enter choice : 1

Enter data : 35

Enter choice : 3

Front element :15

Enter choice : 6

15 25 35

Enter choice : 2

Dequed value : 15

Enter choice : 7
87
Queue size : 2

Enter choice : 4

Queue not empty

Enter choice : 5

Exit

88
RESULT:

Thus the C program to implement queue using linked list was executed successfully and the output
was verified.

89
Ex.No: 6
Date IMPLEMENTATION OF SORTING ALGORITHMS

6.1. BUBBLE SORT

AIM:

To write a C program to implement bubble sort.

ALGORITHM:

(Bubble Sort) BUBBLE (A, N)

Step 1: Start
Step 2: Repeat Steps 3 to 5 for Pass = 1 to N1
Step 3: Set Swapped = 0 and K = 0
Step 4: Repeat while K < (NPass)
(a) if A[K ] >A[ K + 1] then
Interchange A[ K ] and A[ K + 1 ] and
Set Swapped = 1
[End of if structure]
(b) Set K = K + 1
[End of inner loop of step-4]
Step 5: if Swapped = 0 then break the outer loop of step-2
[End of outer loop of step-2]

90
PROGRAM:

#include<stdio.h>
#include<conio.h>
void bubble(int[],int);
void main()
{
int a[20],i,n;
clrscr();
printf("Enter the number of items in the array");
scanf("%d",&n);
printf("Enter the data in the array");
for(i=0;i<n;i+)
{
scanf("%d",&a[i]);
}
bubble(a,n);
getch();
}
void bubble(int a[],int n)
{
int i,temp,j,p;
for(i=1;i<n;i++)
{
for(p=0;p<n-i;p++)
{
if(a[p]>a[p+1])
{
temp=a[p];
a[p]=a[p+1];
a[p+1]=temp;
}
}
}
for(i=0;i<n;i+)
printf("\nSorted Array is: %d",a[i]);
}

91
OUTPUT:

Enter the number of items in the array5


Enter the data in the array34
65
34
23
75

Sorted Array is:


23
34
34
65
75

92
RESULT:

Thus the C program to implement Bubble Sort was executed successfully and the output was verified.

93
6.2. INSERTION SORT

AIM:

To write a C program to implement insertion sort.

ALGORITHM:

Step 1: Read the elements into the array


Step 2: Take the second element. Compare it with the first element. If the second element less than the first
element interchange them
Step 3: Take the third element compare it first and second element and insert it in the correct position by
shifting the elements in the array. So that the first, second and third elements are in sorted array
Step 4: In general take the ith element and compare it with the all the elements before it and place it in the
proper position by shifting the elements one position right.
Step 5: When the ith element is placed, the elements in the array from the 0th to the ith position will be in the
sorted order
Step 6: The above process is continued for all the elements in the array.
Step 7: Stop.

94
PROGRAM:

#include<stdio.h>
#include<conio.h>
void insert(int[],int);
void main()
{
int a[20],i,n;
clrscr();
printf("Enter the number of items in the array");
scanf("%d",&n);
printf("Enter the data in the array");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
insert(a,n);
getch();
}
void insert(int a[],int n)
{
int i,j,temp;
for(i=1;i<n;i++)
{
temp=a[i];
for(j=i-1;j>=0;j--)
{
if(a[j]>temp)
{
a[j+1]=a[j];
}
else
break;
}
a[j+1]=temp;
}
printf("Data After Insertion sort");
for(i=0;i<n;i++)
printf("\n%d", a[i]);
}

95
OUTPUT:

Enter the number of items in the array4


Enter the data in the array56
34
78
23
Data After Insertion sort
23
34
56
78

96
RESULT:

Thus the C program to implement Insertion Sort was executed successfully and the output was verified.

97
6.3. QUICK SORT

AIM:

To write a C program to implement quick sort.

ALGORITHM:

QUICKSORT (A, LEFT, RIGHT)


Step 1: If LEFT RIGHT, then: Return.
Step 2: Set MIDDLE= PARTITION (A, LEFT, RIGHT).
Step 3: Call QUICKSORT (A, LEFT, MIDDLE-1).
Step 4: Call QUICKSORT (A, MIDDLE+1, RIGHT).
Step 5: Return

Algorithm: PARTITION (A, LEFT, RIGHT)


Step 1: Set X= A[LEFT].
Step 2: Set I= LEFT.
Step 3: Repeat for j = LEFT+1, LEFT+2, . . . . . RIGHT
If A[j] < X, then:
Set i= i+1
SWAP (A[i], A[j])
Step 4: SWAP (A[i], A[LEFT].
Step 5: Return i.

98
PROGRAM:

#include<stdio.h>
#include<conio.h>
void quicksort(int[],int,int);
int partition(int[],int,int);
void main()
{
int a[20],i,n;
clrscr();
printf("Enter the number of items in the array");
scanf("%d",&n);
printf("Enter the elements in the array");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}

quicksort(a,0,n-1);
for(i=0;i<n;i++)
printf("\n%d",a[i]);
getch();
}
void quicksort(int a[],int lb,int ub)
{
int mid;
if(lb<ub)
{
mid=partition(a,lb,ub);
quicksort(a,lb,mid-1);
quicksort(a,mid+1,ub);
}
}
int partition(int a[],int lb,int ub)
{

int i,p,q,t;
p=lb+1;
q=ub;
i=a[lb];
while(q>=p)
{
while(a[p]<i)
p++;
while(a[q]>i)
q--;
if(q>p)
{
t=a[p];
a[p]=a[q];

99
a[q]=t;
}
}
t=a[lb];
a[lb]=a[q];
a[q]=t;
return q;
}

100
OUTPUT:
Enter the number of items in the array5
Enter the elements in the array34
56
23
78
14

Data After Quick sort

14
23
34
56
78

101
RESULT:

Thus the C program to implement Quick Sort was executed successfully and the output was verified.

102
6.4. MERGE SORT

AIM:

To write a C program to implement merge sort.

ALGORITHM:

Algorithm mergeSort(A, i, j)
1. if i < j then
2. mid i+j
3. mergeSort(A, i,mid)
4. mergeSort(A,mid + 1, j)
5. merge(A, i,mid, j)

Algorithm merge(A, i, mid, j)


1. initialise new array B of length j i + 1
2. k i; c mid + 1; m 0
3. while k mid and c j do
4. if A[k].key A[c].key then
5. B[m] A[k]
6. kk+1
7. else
8. B[m] A[c]
9. cc+1
10. m m + 1
11. while k mid do
12. B[m] A[k]
13. k k + 1
14. m m + 1
15. while j do
16. B[m] A[c]
17. c c + 1
18. m m + 1
19. for m = 0 to j i do
20. A[m + i] B[m]

103
PROGRAM:

#include<stdio.h>
#include<conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int main()
{
int arr[30];
int i,size;
printf("\n\t------- Merge sorting method -------\n\n");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
printf("\n\t------- Merge sorted elements -------\n\n");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
return 0;
}

void part(int arr[],int min,int max)


{
int mid;
if(min<max)
{
mid=(min+max)/2;
part(arr,min,mid);
part(arr,mid+1,max);
merge(arr,min,mid,max);
}
}

void merge(int arr[],int min,int mid,int max)


{
int tmp[30];
int i,j,k,m;
j=min;
m=mid+1;
for(i=min; j<=mid && m<=max ; i++)
{
if(arr[j]<=arr[m])
{

104
tmp[i]=arr[j];
j++;
}
else
{
tmp[i]=arr[m];
m++;
}
}
if(j>mid)
{
for(k=m; k<=max; k++)
{
tmp[i]=arr[k];
i++;
}
}
else
{
for(k=j; k<=mid; k++)
{
tmp[i]=arr[k];
i++;
}
}
for(k=min; k<=max; k++)
arr[k]=tmp[k];
}

105
OUTPUT

------- Merge sorting method -------

Enter total no. of elements : 4


Enter 1 element : 67
Enter 2 element : 45
Enter 3 element : 37
Enter 4 element : 34

------- Merge sorted elements -------

34 37 45 67

106
RESULT:

Thus the C program to implement Merge Sort was executed successfully and the output was verified.

107
Ex.No: 7
Date IMPLEMENTATION OF SEARCHING ALGORITHMS

7.1. LINEAR SEARCH

AIM:

To write a C program to implement linear search.

ALGORITHM:

Step 1: Start the program

Step 2: Define function for linear search as

a) Read the data to be searched X


b) Scan the array from the left to right
c) Compare X with the first element
d) If equal then
Print The number is found and return
Else
Compare X with second element and so on.
Step 3: Stop the program

108
PROGRAM:

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

int a[10],i,n,m,c=0;

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");

return 0;
}

109
OUTPUT:

Enter the size of an array: 5

Enter the elements of the array: 4 6 8 0 3

Enter the number to be search: 0

The number is found

110
RESULT:

Thus the C program to implement Linear Search was executed successfully and the output was verified.

111
7. 2. BINARY SEARCH

AIM:

To write a C program to implement binary search.

ALGORITHM:

Step 1: Start the program

Step 2: Define function for Binary Search as

a) Sort the array in ascending order


b) Let lb=0 and ub=n-1
c) Read the data to be searched X
d) Find the mid position of the given array
Mid=(lb+ub)/2
e) Compare X with a[mid]
If equal then
Goto step (g)
Else
If X less than a[mid] then ub=mid-1
If X greater than a[mid] then lb=mid+1
f) If lb<=ub
Repeat steps (d) and (e) for the sub array lb to ub
Else
Goto step (g)
g) If(lb>ub)
Print Search Success
Else
Print Search Failed
h) Return

Step3: Stop the program.

112
PROGRAM

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

int a[10],i,n,m,c=0,l,u,mid;

printf("Enter the size of an array: ");


scanf("%d",&n);

printf("Enter the elements in ascending order: ");


for(i=0;i<n;i++){
scanf("%d",&a[i]);
}

printf("Enter the number to be search: ");


scanf("%d",&m);

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.");

return 0;
}

113
OUTPUT:

Enter the size of an array: 5

Enter the elements in ascending order: 4 7 8 11 21

Enter the number to be search: 11

The number is found.

114
RESULT:

Thus the C program to implement Binary Search was executed successfully and the output was
verified.

115

You might also like