/* NM i programmering 2001 Løsningsforslag til oppgave F Skrevet av Dag Langmyhr (dag@ifi.uio.no) */ #include /* find_instr: A recursive function to find the instructions needed to produce the value x. These instructions are printed to f. */ void find_instr (FILE *f, int x) { if (x < -1 || x > 1) { if (x%2 == 0) { find_instr(f, x/2); fprintf(f, "DBL\n"); } else { find_instr(f, x-1); fprintf(f, "INCR\n"); } } else { fprintf(f, "%s\n", (x<0 ? "C-1" : "C+1")); } } /* main: The main program. It will read various numbers and use find_instr to print the instructions resulting in the number. */ int main (void) { FILE *in_f = fopen("yacl.in","r"), *out_f = fopen("yacl.out","w"); int x, n_printed = 0; for (fscanf(in_f,"%d",&x); x != 0; fscanf(in_f,"%d",&x)) { if (n_printed++ > 0) fprintf(out_f, "\n"); fprintf(out_f, "Constant %d\n", x); find_instr(out_f, x); } fclose(in_f); fclose(out_f); return 0; }