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

Popular posts from this blog

Slip 22_2: 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 sentinel 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 :

Slip10_2, 30_1 : Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp) using bubble sort or selection sort

Slip 23_2: Read the data from file ‘sortedcities.txt’ containing sorted names of cities and their STD codes. Accept a name of the city from user and use binary search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not in the list”.