20ESPL101 Programming in C Lab Manual
20ESPL101 Programming in C Lab Manual
S.
LIST OF EXPERIMENTS
NO
1. Programming using I/O statements and Expressions
a) Program to display your personal details
b) Program to get the user details and display it
2. a) Program to display biggest of three numbers.
b) Program to check whether the entered character is vowel or not
3. Program to find whether given year is leap year or not
4. Program to perform the calculator operation using switch case
5. Program to check whether a given number is Armstrong or not
6. Program to check whether a given number is odd or not
7. Program to find factorial of given number
8. Program to find out average of n-numbers
9. Program to find largest element in an array
10. Program to perform Matrix addition
11. Program to perform String operations
12. Program to perform search operations such as linear search & Binary search using functions
13. Program to perform swapping using call by value & call by reference
14. Program to perform Fibonacci series using recursion
15. Program to perform sorting names using arrays and pointers
16. Program to display employee details using Structures
17. Program to display 5 student details and calculate total, average and display result using
Structures and Pointer Structure
18. Program to display student details using Union.
19. Program to count the number of words and characters in a file
20. Telephone directory using random access file
2
EX1
PROGRAMUSINGI/OSTATEMENTSANDEXPRESSIONS
DATE:
AIM:
i] Programtodisplayyourpersonaldetails
ALGORITHM:
Step1: Start
Step2:Declareandinitializethevariablesforname,address,dateofbirth,mobilenumber
andage
Step3:Displayname,address,
dateofbirth,mobilenumberandageStep4:End
PROGRAM:
#include<stdio.h>
voidmain()
{
charname[20]="SAIRAM";
char address[80]= "west
tambharam,chennai";intdate=20;
int
month=10;intye
ar=1990;
int
mobile=987456321;int
age=25;
printf("\n=====================");
printf("\n NAME:
%s",name);printf("\nADDRESS:
%s",address);
printf("\n DOB:%d:%d:%d", date , month,
year);printf("\n MOBILE NUMBER:%d",
mobile);printf("\n AGE:%d", age);printf("\
n=====================");
}
3
OUTPUT:
NAME:SAIRAM
ADDRESS:westtambaram,chennai
DO[Link]
MOBILE
NUMBER:987456321AGE:25
RESULT
Thus the C Program to display the personal details has been executed and the output
wasverified.
4
AIM:
ii] Programtogettheuserdetailsanddisplayit.
ALGORITHM:
Step1: Start
Step2:Declarethevariablesforname,address,date,month,year,mobilenumber,age.
Step3:Readvaluesofname, address,date,month,year,mobilenumber, agefromthe
user.
Step4:Displayname,address,date,month,year,
mobilenumber,age.Step5:End
PROGRAM:
#include<stdio.h>
#include<conio.h
>#include<string.
h>intmain()
{
charname[20];ch
ar
address[80];intd
ate;
int
month;int
year;
longint
mobile;char
gender[20];inta
ge;
printf("\nENTERYOURNAME:=");
gets(name);
printf("\nENTERYOURADDRESS=");
gets(address);
printf("\nENTER YOUR
date/month/year=");scanf("%d/%d/%d",&dat
e,&month,&year);printf("\n ENTER YOUR
AGE=");scanf("%d",&age);
printf("\nENTERYOURGENDER(MALE/FEMALE)=");
scanf("%s",gender);
printf("\nENTERYOURMOBILENUMBER=");
scanf("%ld",&mobile);
5
printf("\n=====================");
printf("\n NAME:
%s",name);printf("\nADDRESS:
%s",address);
printf("\n DOB:%d:%d:%d", date , month,
year);printf("\nAGE:%d",age);
printf("\nGENDER:%s",gender);
printf("\n MOBILE NUMBER:%d",
mobile);printf("\
n=====================");
return0;
}
OUTPUT:
ENTERYOURNAME:=karthikeyan
ENTERYOURADDRESS=westtambharam,chennai.E
NTERYOURdate/month/year=03/12/1992
ENTERYOURAGE=28
ENTERYOURGENDER(MALE/
FEMALE)=MALEENTERYOURMOBILENUMBER
=987654321
=====================
NAME:karthikeyanADDRESS:westt
ambharam,[Link][Link]
AGE:28GENDE
R:MALE
MOBILENUMBER:987654321
========================
RESULT:
EX2A
PROGRAMTODISPLAYBIGGESTOFTHREENUMBERS
DATE:
AIM:
ii]Programtocheckbiggestofthreenumbers
ALGORITHM:
Step1:Start
Step3: Check whether A is greater than B and then check whether A is greater than C then
print A is greater
Step8:end
PROGRAM:
#include
<stdio.h>voidmai
n()
{
intA,B,C;
printf("Enter 3 integer number \
n");scanf("%d",&A);
scanf("%d",&B);
scanf("%d",&C);
if(A>B){
if(A>C){
printf("%d istheGreatestNumber\n",A);
}
else{
printf("%disthegreatestNumber\n",C);
}
8
}
else{
if(B>C){
printf("%disthegreatestNumber\n",B);
}
else{
printf("%disthegreatestNumber\n",C);
}
}
}
OUTPUT:
RESULT:
Thus the C Program to display the personal details has been executed and the output
wasverified.
9
AIM:
ii]Programtocheckwhethertheenteredcharacter isvowelornot(Useswitchcase)
ALGORITHM:
Step1: Start
Step2:Declarevariables
Step3:Gettheinputfromtheuserandcompare witheachcases
Step5:End
PROGRAM:
#include<stdio.h>
#include<conio.h
>intmain()
{
charch;
printf("Enter a character:
");scanf("%c",&ch);
//condition to check character is alphabet or
notif((ch>='A'&&ch<='Z')||(ch>='a'&&ch<='z'))
{
switch(ch)
{
case'A':
case'E':
case'I':
case'O':
case'U':
case'a':
case'e':
case'i':
case'o':
case'u':
printf("%cisaVOWEL.\n",ch);
10
break;
default:
printf("%cisaCONSONANT.\n",ch);
}
}
else
{
printf("%cisnot analphabet.\n",ch);
}
return0;
}
OUTPUT:
Enter a
characterE
Eis avowelEnter
a characterX
X is a
consonantEntera
character
+isnotanalphabet
RESULT:
Thus the C Program check whether the entered character is vowel or not (Use
switchcase) has beenexecutedand theoutputwas verified.
11
AIM:
TowriteaCProgramtofindwhetherthegiven yearisleapyearornot.
ALGORITHM:
Step1:Start
Step2:Takeintegervariableyear
Step3:Checkifyearisdivisibleby400thenDISPLAY"isaleapyear"
Step4:Checkifyearis notdivisibleby100ANDdivisibleby4thenDISPLAY"isaleapyear"
Step5:Otherwise,DISPLAY"isnotaleapyear"Step
6:Stop
PROGRAM:
#include<stdio.h>#
include
<conio.h>voidmai
n()
{
intyear;
printf("Enter a year :\
n");scanf("%d",&year);
if((year% 400)==0)
printf("%disaleapyear\n",year);else
if((year%100)!=0&&(year
%4)==0)printf("%disa leapyear\n",year);
else
printf("%disnotaleapyear \n",year);
}
12
OUTPUT:
Enterayear:
2000
2000isaleapyear
Enterayear:
1900
1900isnotaleapyear
RESULT:
Thus the C Program to find whether the given year is leap year or not has
beenexecutedsuccessfullyand theoutputwas verified.
13
AIM:
ToperformtheCalculatoroperations,namely,addition,subtraction,multiplication,divisi
onandsquareofanumber
ALGORITHM:
Step 2 : Declare the variables and display menu for arithmetic operation
Step3: Gettheinputvalues
Step4:Performtheoperationsusingswitch case
Step5:Printtheresults
Step6:Stoptheprogram
PROGRAM:
#include<stdio.h>
#include<conio.h>
int main()
{
inta,b;
int op;
printf(" [Link]\n [Link]\n [Link]\n [Link]\n");
printf("Enter the values of a & b: ");
scanf("%d %d",&a,&b);
printf("Enter your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1 :
printf("Sum of %d and %d is : %d",a,b,a+b);
break;
case 2 :
printf("Difference of %d and %d is : %d",a,b,a-b);
break;
case 3 :
printf("Multiplication of %d and %d is : %d",a,b,a*b);
break;
case 4 :
printf("Division of Two Numbers is %d : ",a/b);
break;
14
default :
printf(" Enter Your Correct Choice.");
break;
}
return 0;
}
OUTPUT:
[Link]
[Link]
[Link]
[Link]
Enter the values of a & b: 20 15
Enter your Choice : 1
Sum of 20 and 15 is : 35
RESULT
ThustheCProgramtoperformtheCalculatoroperations,namely,addition,subtraction,
multiplication, division and square of a number has been executed and results areverified.
15
EX5 PROGRAMTOCHECKWHETHERAGIVENNUMBERISAR
MSTRONGNUMBER ORNOT?
DATE:
EX5:
AIM:
Programtocheck whetherthegivennumberisArmstrongnumberornot
ALGORITHM:
Step1: Start
numStep3:ReadnumfromUser
Step4:InitializeVariablesum=0andtemp=num
Step 5: Repeat the flowing steps 6 & 7 Until the value of num is 0
Step 6: Calculate the remainder value by using modulo operator
Step 7: cube the remainder value and its added with sum. Then
Number is decremented by dividing the num value by 10.
Step8:IFsum==tempPrint"ArmstrongNumber"ELSEPrint"NotArmstrongNumber"
Step9:Stop
PROGRAM:
#include<stdio.h>
intmain()
{
intnum,copy_of_num,sum=0,rem;printf("\
nEnter a number:");scanf("%d",&num);
while(num!=0)
{
rem=num%10;
sum=sum+
(rem*rem*rem);num=num/10;
}
if(copy_of_num==sum)
printf("\n%disanArmstrongNumber",copy_of_num);else
printf("\n%disnotanArmstrongNumber",copy_of_num);return(0);
}
16
OUTPUT:
Enteranumber: 370
370isanArmstrongNumber
RESULT:
Thus the C Program to check whether a given number is Armstrong or not has
beenexecutedandtheoutputwas verified.
17
EX6 PROGRAMTOCHECKWHETHERAGIVENNUMBERIS
ODDOREVEN
DATE:
AIM:
Programtocheckwhetheragivennumberisoddoreven
ALGORITHM:
programStep2:
Getthenumber
Step3:Check thenumberifitisoddorevenusingifstatement.
Step4:Ifthenumberisevencheck theconditionasn
%2==0elseitiseven.Step5:Displaytheresult
PROGRAM:
#include
<stdio.h>intmain(
int number;
printf("Enter an integer:
");scanf("%d",&number);
0)printf("%dis even.",number);
else
printf("%d is odd.",
number);return0;
18
}
19
OUTPUT:
Enteraninteger:-7
-7isodd.
Enter an integer :
88is even
RESULT
ThustheCProgramtofindwhetherthegivennumberisoddorevennumberhasbeensuccessfullyexecut
edandverified
20
EX7
PROGRAMTOFINDFACTORIALOFAGIVENNUMBER
DATE:
AIM:
Tofindfactorialofa givennumber
ALGORITHM:
[Link]
number
factorial”[Link]←1i←1
Step 5. Readvalueofn
Step 7:Displayfactorial
Step 8. Stoptheprogram
PROGRAM:
intmain()
int n, i; longfactorial =
1;printf("Enter an integer:
");scanf("%d",&n);
//
showerroriftheuserentersanegativeintegerif(n<0
)
printf("Error! Factorial of a negative number doesn't
exist.");else
{
21
for(i=1;i<=n;++i)
{
factorial*=i;
//factorial=factorial*i;
}
printf("Factorialof%d=%lu",n,factorial);
}
return0;
}
OUTPUT:
Enter an integer:
10Factoriaof10=3628800
RESULT
ThustheCProgramtofindthe
factorialofagivennumberhasbeensuccessfullyexecutedandverified.
22
EX8
PROGRAMTOFIND OUTTHEAVERAGEOFn -INTEGERS
DATE:
AIM:
Tofindaverageof4 integers
ALGORITHM:
[Link]
[Link]
[Link]=sum/n
[Link]
PROGRAM:
#include<stdio.h>
voidmain()
inti,n,sum=0,nu[100];
floatavg;
clrscr();
printf("\nEnterthenumbers\n");
for(i=0;i<n;i++)
scanf("%d",&nu[i]);
sum=sum+ nu[i];
}
23
avg=(float)sum/n;
printf("\nAverage is : %.2f\
n",n,avg);getch();
}
OUTPUT:
Enter the
numbers32
45
54
22
Average is38.25
RESULT
ThustheCProgramtofindtheaverageof4numbershasbeenexecutedandverified.
24
EX9
PROGRAM TO FIND LARGEST ELEMENT IN AN ARRAY
DATE:
AIM:
ALGORITHM:
Step1:Starttheprogram
STEP 6: if(arr[i]>max)
max=arr[i]
STEP 7: i=i+1.
STEP 9: RETURN 0
Step10: Stoptheprogram
PROGRAM:
#include <stdio.h>
int main()
{
intarr[] = {25, 11, 7, 75, 56};
int length = sizeof(arr)/sizeof(arr[0]);
int max = arr[0];
OUTPUT:
RESULT:
Thus the C Program to find the largest number in an array has been
executedandtheresultwas verified
26
EX10
PROGRAMTOPERFORM MATRIX ADDITION
DATE:
AIM:
ALGORITHM:
Step1:Starttheprogram
elementsStep5:Stoptheprogram
PROGRAM:
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i< r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}
return 0;
}
OUTPUT:
10 8 6
RESULT:
EX11
AIM:
ALGORITHM:
Step1:Start
Step2:GetthetwoStrings str1 and str2.
Step3: perform various string operation
.Step4: to find string length, use strlen(str1) function
Step5:To find Uppercase of string use strupr(str1)
.Step6:To find concatenation, use strcat(str1,str2)
Step 7 :To copy the string, use strcpy(str3,str1)
Step8:Stop
PROGRAM:
# include <stdio.h>
# include <conio.h>
# include <string.h>
int main()
{
char str1[40], str2[40] ;
clrscr() ;
printf("Enter the first string : \n\n") ;
gets(str1) ;
printf("\nEnter the second string : \n\n") ;
gets(str2) ;
printf("\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Length is : %d and %d", strlen(str1), strlen(str2)) ;
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Uppercase is : %s and %s", strupr(str1), strupr(str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Lowercase is : %s and %s", strlwr(str1), strlwr(str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Reverse is : %s and %s", strrev(str1), strrev(str2)) ;
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- String copy is : %s ", strcpy(str1,str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
printf("- Concatenation is : %s ", strcat(str1,str2));
printf("\n\nString 1 = %s & String 2 = %s ", str1, str2) ;
return 0 ;
}
29
OUTPUT:
RESULT:
ThustheCProgramtoperformstring
operationshasbeenexecutedandtheresultwasverified.
30
EX12 a
PROGRAM TO PERFORM SEARCH OPERATIONS SUCH
AS LINEAR SEARCH USING FUNCTIONS
DATE:
AIM:
ALGORITHM:
Step1: Start
Step 2: Initialize current element with first element of the list.
Step 3: Compare current element with the key. If they are equal, goto Step 5
Step 4: Set next element, if present, as current element and goto Step 2
Step 5: All elements are traversed and no element of array matches key. So, key not found.
Return -1
Step 6: Key is found. Return the position of the element
Step 7: Stop
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
/*
Input : integer array indexed from 0, key to be searched
Ouput : Position of the key in the array if found, else -1
*/
intlinearSearch(int a[], int n, int key) {
intpos = -1;
for (inti = 0; i< n; ++i) {
if (a[i] == key) {
pos = i;
break;
}
}
returnpos;
}
int main() {
int a[] = {8, 12, 3, 4, 7, 2, 13};
int n = sizeof(a) / sizeof(a[0]);
intpos = linearSearch(a, n, 3);
if (pos != 1)
printf("Key found at position : %d \n", pos);
else
31
printf("Key not found \n");
return 0;
}
OUTPUT:
RESULT:
EX12 b
PROGRAM TO PERFORM SEARCH OPERATIONS SUCH
AS BINARY SEARCH USING FUNCTIONS
DATE:
AIM:
ALGORITHM:
Step1: Start
Step2:Compare the middle element of the search space with the key.
Step3:If the key is found at middle element, the process is terminated.
Step4:If the key is not found at middle element, choose which half will be used as the next
search space.
If the key is smaller than the middle element, then the left side is used for next
search.
If the key is larger than the middle element, then the right side is used for next
search.
Step5:This process is continued until the key is found or the total search space is exhausted.
Step 6: Stop
PROGRAM:
#include <stdio.h>
// Driver code
int main(void)
{
intarr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1) ? printf("Element is not present"
" in array")
: printf("Element is present at "
"index %d",
result);
return 0;
}
OUTPUT:
RESULT:
EX13
PROGRAM TOPERFORMSWAPPINGUSINGCALL BY VALUE &
CALL BY REFERENCE
DATE:
AIM:
ALGORITHM:
Step1. Starttheprogram
Step2.
Declareandgetthetwointegervariablesaandb.Step3.
Calltheswappingfunction
PROGRAM:
/* Call by Value */
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
/* Call by Reference */
#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
swap(&a,&b);
printf("After swapping values in main a = %d, b = %d\n",a,b);
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters,
a = 20, b = 10
}
OUTPUT:
/* Call by Value */
RESULT:
ThustheCProgramtoswaptwonumbersusingcall by value and
referencehasbeenexecutedandverified
36
EX14
PROGRAM TO PERFORM FIBONACCI SERIES USING
DATE: RECURSION
AIM:
Todisplayallprimenumbersbetweentwointervalsusingfunctions
ALGORITHM:
Step5:StoptheProgram
PROGRAM:
#include<stdio.h>
voidprintFibonacci(int n){
staticint n1=0,n2=1,n3;
if(n>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printf("%d ",n3);
printFibonacci(n-1);
}
}
int main(){
int n;
printf("Enter the number of elements: ");
scanf("%d",&n);
printf("Fibonacci Series: ");
printf("%d %d ",0,1);
37
printFibonacci(n-2);//n-2 because 2 numbers are already printed
return 0;
}
OUTPUT:
RESULT:
EX15
PROGRAMTO PERFORM SORTING NAMES USING ARRAYS
DATE: AND POINTERS
AIM:
ALGORITHM:
Step1: Start
Step2:Declarethe String
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *x[20];
inti,n=0;
void reorder(intn,char *x[]);
clrscr();
printf("Enter no. of String : ");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;i++)
{
printf("Enter the Strings %d : ",i+1);
x[i]=(char *)malloc(20*sizeof(char));
scanf("%s",x[i]);
}
reorder(n,x);
printf("\nreorder list is : \n");
for(i=0;i<n;i++)
{
printf("%d %s\n",i+1,x[i]);
}
getch();
}
void reorder(intn,char *x[])
{
39
inti,j;
char t[20];
for(i=0;i<n-1;i++)
for(j=i+1;j<n;j++)
if(strcmp(x[i],x[j])>0)
{
strcpy(t,x[j]);
strcpy(x[j],x[i]);
strcpy(x[i],t);
}
return;
}
OUTPUT:
Enter no of strings: 5
Enter the String 1: Priya
Enter the String 2: Ram
Enter the String 3: Arjun
Enter the String 4: Maheshwari
Enter the String 5: Revathi
1 Arjun
2 Maheshwari
3 Priya
4 Ram
5 Revathi
RESULT
ThustheCProgramtoperform sorting names using arrays and
pointershasbeenexecutedandverified
40
41
EX16
PROGRAM TO DISPLAY EMPLOYEE DETAILS USING
STRUCTURES
DATE:
AIM:
ALGORITHM:
Step1:START
Step2:Reademployee’s details like name, employee id and salary using
structureStep3: Display the entered values
Step 4: STOP
PROGRAM:
#include <stdio.h>
/*structure declaration*/
struct employee{
char name[30];
intempId;
float salary;
};
int main()
{
/*declare structure variable*/
struct employee emp;
OUTPUT:
Enter details :
Name ?:Mike
ID ?:1120
Salary ?:76543
RESULT:
ThustheCProgramtostoreanddisplayemployeedetailsusingstructureshasbeenexecutedand
theresultwas verified.
43
AIM:
Toreadthestudentdataandcalculatethetotalmarks
ALGORITHM:
Step1:Starttheprogram
subjectsStep3:Calculate thetotalmarksofeachstudent
Step4:Calculatethestudentwho
gotthehighesttotalmarksStep5:Displaytheresults
Step6:StoptheProgram
PROGRAM:
#include<stdio.h>
structstudent
int
sub1;int
sub2;int
sub3;int
sub4;int
sub5;
};
voidmain()
struct student
s[10];inti,total=0;
44
clrscr();for(i=0;i
<=4;i++)
printf("\nEnterMarksinFiveSubjects=");
scanf("%d%d
%d",&s[i].sub1,&s[i].sub2,&s[i].sub3,&s[i].sub4,&s[i].sub5);total=s[i].sub
1+s[i].sub2+s[i].sub3+s[i].sub4+s[i].sub5;
printf("\nTotalmarksofs[%d]Student=%d",i,total);
getch();
OUTPUT:
Subjects8070908098
TotalMarks of1student=83.6
Subjects6075505578
TotalMarks of2student=63.6
Subjects7070907568
TotalMarks of3student=74.6
RESULT:
ThustheCProgramtoprintthestudentdetailshasbeenexecutedandtheresultwasverified.
45
DATE:
AIM:
ALGORITHM:
Step1:Starttheprogram
Step3:Displaytheresults
Step4:StoptheProgram
PROGRAM:
union un {
int member1;
char member2;
float member3;
};
// driver code
int main()
{
return 0;
}
OUTPUT:
The value stored in member1 = 15
RESULT:
ThustheCProgramtoprintthestudentdetailsusing union
hasbeenexecutedandtheresultwasverified.
46
AIM:
ALGORITHM:
Step1:Starttheprogram
Step 6: Repeat all these steps till all the lines from the
Step 7:StoptheProgram
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
int main()
{ charch;
FILE *file;
int count = 0;
return 0;
}
OUTPUT:
Number of words present in given file: 63
RESULT:
EX:20
TELEPHONEDIRECTORYUSINGRANDOMACCESSFILE
DATE:
AIM:
To insert, update, delete and append telephone details of an individual or a company into
atelephonedirectoryusing random access file.
ALGORITHM:
Step1:Createarandom accessfile
Step 2:call the respective procedure to insert, update, delete or append based on user
choiceStep3: Access therandom access file tomakethenecessarychanges andsave
PROGRAM
#include
"stdio.h"#include
"string.h"#include
<stdlib.h>#include
<fcntl.h>
structdir
{
char
name[20];charnu
mber[10];
};
void insert(FILE
*);void update(FILE
*);void del(FILE
*);void display(FILE
*);voidsearch(FILE*)
;
int record =
0;int
main(void)
{intchoice=0;
FILE*fp=fopen("[Link]","rb+");
if (fp == NULL ) perror ("Error opening
file");while(choice!=6)
{
printf("\n1 insert\t 2 update\
n");printf("3delete\t4display\
n");
printf("5 search\t 6 Exit\n Enter
choice:");scanf("%d",&choice);
switch(choice)
{
case 1: insert(fp);
break;case 2: update(fp);
break;case3:
del(fp);break;case 4:
49
display(fp); break;case 5:
search(fp);
break;default:;
}
}
50
fclose(fp);
return0;
}
voidinsert(FILE*fp)
{
structdircontact,blank;
fseek( fp, -sizeof(structdir),
SEEK_END );fread(&blank,
sizeof(structdir), 1, fp);printf("Enter
individual/company name:
");scanf("%s",[Link]);
printf("Enter telephone number:
");scanf("%s",[Link]);fwrite(&cont
act,sizeof(structdir),1,fp);
}
voidupdate(FILE*fp)
{
char name[20],
number[10];intresult;
structdir contact,
blank;printf("Enter
name:");scanf("%s",
name);rewind(fp);while
(!feof(fp))
{
result = fread(&contact, sizeof(structdir), 1,
fp);if(result!=0&&strcmp(name,[Link]) ==
0)
{
printf("Enter
number:");scanf("%s",
number);strcpy([Link],nu
mber);
fseek(fp, -sizeof(structdir),
SEEK_CUR);fwrite(&contact,
sizeof(structdir), 1,
fp);printf("Updatedsuccessfully\n");
return;
}
}
printf("Recordnotfound\n");
}
voiddel(FILE*fp)
{
char name[20],
number[10];intresult,
record=0;
structdir contact, blank = {"",
""};printf("Entername:");
scanf("%s",
name);rewind(fp);
51
while(!feof(fp))
{
result = fread(&contact, sizeof(structdir), 1, fp);
voiddisplay(FILE*fp)
{
structdir
contact;int
result;rewind(fp)
;
printf("\n\n Telephone directory\
n");printf("%20s %10s\n", "Name",
"Number");printf("*************************
******\n");while(!feof(fp))
{
result = fread(&contact, sizeof(structdir), 1,
fp);if(result != 0 &&strlen([Link]) >
0)printf("%20s%10s\
n",[Link],[Link]);
}
printf("*******************************\n");
voidsearch(FILE*fp)
{
structdircontact;
int result; char
name[20];rewind(fp);pri
ntf("\nEnter
name:");scanf("%s",nam
e);
while(!feof(fp))
{
result = fread(&contact, sizeof(structdir), 1,
fp);if(result!=0 &&strcmp([Link],name)==
0)
{
printf("\n%20s %10s\n",[Link],
[Link]);return;
}
}
printf("Recordnotfound\n");
}
53
OUTPUT:
1insert 2update
54
3delete 4display
5search 6Exit
Enter choice:
4Telephonedirector
y
Name Number
******************************
*bb 11111
*******************************
1insert 2 update
3delete 4display
5search 6Exit
Enter choice:
5Entername:bb
bb 11111
1insert 2 update
3delete 4display
5search 6Exit
Enterchoice:1
Enter individual/company
name:aaEntertelephonenumber:222
222
1insert 2 update
3delete 4display
5search 6Exit
Enter choice:
2Entername:aa
Enter number:
333333Updated
successfully
1insert 2 update
3delete 4display
5search 6
ExitEnterchoice:
Telephonedirectory
Name Number
******************************
*bb 11111
aa 333333
******************************
*1insert 2 update
55
3delete 4display
5search 6Exit
56
Enterchoice:3
Entername:aa
1 Deleted successfully
1insert 2update
3delete 4display
5search 6Exit
Enterchoice:4
Telephonedirectory
Name Number
******************************
*bb 11111
*******************************
1insert 2 update
3delete 4display
5search 6Exit
Enterchoice:6
RESULT:
ThustheCprogramtoinsert,update,deleteandappendtelephonedetailsofanindividual or a
company into a telephone directory using random access file was successfullywrittenand
executed.