CSC195, Class 34: More on Exam 2 and readLine Overview: * readLine + Testing, continued + An incorrect solution + Developing a correct solution * Efficient exponentiation * strncpy Notes: * Happy April Fool's day! * Rearranging schedule so that there's not a gap in this discussion. * Read Gries 10 for tomorrow. ---------------------------------------- What kinds of tests should we put in the file we're reading: * Ones in which the string we're reading is less than max characters empty line other things in between max-1 equal to max characters more than max characters at least twice as many ---------------------------------------- int readLine(FILE *file, char string[], int max) { char c; int i; for(i = 0; ((c=getc(file))!=EOF) && (c != '\n') && (i < max-1); i++) string[i] = c; string[i++] = '\0'; if (i >= max) return 0; else if (c == EOF) return 1; else if (c == '\n') return 1; else return 0; } /* readLine(FILE *, char[], int) */ ---------------------------------------- Iterative efficient exponentiation x^2k = (x^k)^2 x^(k+1) = x * x^k x^0 = 1 double expt1(double base, int power) { int tmp; if (power == 0) return 1; else if (power % 2 == 0) { tmp = expt1(base, power/2); return tmp*tmp; } else return base * expt1(base, power-1); } O(log_2(n)) How do we make this iterative (using loops)? Two key ideas: x^2k = (x^2)^k x^(k+1) = x * x^k We can accumulate those extra base*'s in another variable double expt2(double base, int power) { double extra = 1; /* original_base^original_power = extra*base^power */ while (power > 1) { if (power % 2 == 0) { base = base*base; power = power/2; } /* original_base^original_power = extra*base^power */ else { extra = base * extra; power = power-1; } /* original_base^original_power = extra*base^power */ } /* original_base^original_power = extra*base^power */ return extra*base; } /* expt2(double, int) */ How would we write a test program for this? (1) Print some values you know 2^3 2^10 2^100 (NOT) Use a variety of exponents and compare to the result from the function in math.h