Thursday, April 30, 2009

sol tut9 ecp1026

/* t9.c : command line call using "t9 t9data" */
#include
#include
#define NDATA 10
struct ivdata{
float volt;
float amp;};
int linSearch (float, struct ivdata [],int);
int binSearch (float, struct ivdata [],int, int);
void readData (struct ivdata [],int);
void printData (struct ivdata [],int);
struct ivdata Data[NDATA];
FILE *in;
int main (int argc, char *argv[])
{
int res1,res2;
float input;
if (argc!= 2)
{ fprintf(stderr,"Usage: \n\t%s \n",argv[0]);
exit(1);}
in = fopen(argv[1],"r");
if (in == NULL)
{ perror("opening input file");
exit(1);}
readData(Data,NDATA);
printData(Data,NDATA);
//search voltage that matched the searched current
printf("Enter the voltage value to search?\n");
scanf("%f",&input);
//Call search functions,store results in res1,res2
res1=linSearch(input,Data,NDATA);
res2=binSearch(input,Data,0,NDATA-1);
if (res1!=-1)
printf("Linear search:V=%2.2f,I=%2.2f\n",Data[res1].volt,Data[res1].amp);
else printf("Not found!\n");
if (res2!=-1)
printf("Binary search:V=%2.2f,I=%2.2f\n",Data[res2].volt,Data[res2].amp);
else printf("Not found!\n");
return 0;
}

void readData (struct ivdata data[],int N){
int j=0;
float i,v;
while (j{ //read data from file, 2 data points in each iteration
fscanf(in,"%f %f",&v,&i);
data[j].volt=v;
data[j].amp=i;
j++;
}
}
//print the data in 2-column format
void printData (struct ivdata data[],int N){
int i ;
for ( i=0 ; iprintf("%2.2f ; %2.2f\n",data[i].volt,data[i].amp);
}
int linSearch (float x, struct ivdata data[],int N){
int j;

for(j=0; j if( data[j].volt == x)
return(j);
}
return(-1);
}

int binSearch (float x, struct ivdata data[],int start, int end)
{
int mid=(start+end)/2;
float result=data[mid].volt;

if(result==x){ printf("%d\n", mid); return(mid);}
if(start>end) return(-1);

if(result<0)

return(binSearch(x,data,start,mid-1));
else
return(binSearch(x,data,mid+1,end));
}

No comments: