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 :

 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 sentinelsearch(struct city a[10],int n,int sr)

{ int i,cnt=0;

 a[n]=sr;

 while(strcmp(sr,a[i].name)!=0)

{ i++;

 }

 if(i<n)

 printf("city is found and STD code is %d ",a[i].code);

 else

 printf("city is 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);

 SentinelSearch(ct,n,sr);

 }

}

Comments

Popular posts from this blog

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 10_1 ,22_1: Implement a linear queue library (st_queue.h) of integers using a static implementation of the queue and implementing the init(Q), add(Q) and peek(Q) operations. Write a program that includes queue library and calls different queue operations