Slip 12_1 : Read the data from file 'cities.txt' containing names of cities and their STD codes. Accept a name of the city from user and use linear search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not in the list”.
Solution :
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct city
{
char name[20];
int code;
}ct[10];
int readFile(struct city a[])
{
int i=0;
FILE *fp;
if((fp=fopen("city.txt","r"))!=NULL)
{
while(!feof(fp))
{
fscanf(fp,"%s%d",&a[i].name,&a[i].code);
i++;
}
}
return i-1;
}
void linearsearch(struct city a[10],int n,char sr[20])
{ int i,p,cnt=0;
for(i=0;i<n;i++)
{
if(strcmp(a[i].name,sr)==0)
{ p=i; //store position
cnt++;
break;
}
}
if(cnt>=1)
printf("city is found and code is %d ",a[p].code);
else
printf("city NOT found ");
}
main()
{ int n;
char sr[20];
n=readFile(ct);
if(n==-1)
printf("File not found ");
else
{
printf("Enter city name to search ");
scanf("%s",sr);
linearsearch(ct,n,sr);
}
}
Comments
Post a Comment