Name: _____________________________________________ Score: ____________ Mathematics 1201: Programming in C Model Solutions to Final Examination Prof. Wickerhauser In Problems 1--7 below, find the value of `x' after all of the statements are executed. Assume all standard library function calls succeed: Problem 1. int x = 12, y = 5; Answer 1: 1 x /= y-- + 2; Problem 2. int i, x; Answer 2: 33 for ( x = i = 3; i; i-- ) x += 0xa; Problem 3. struct { Answer 3: 9 int d; float or[4]; } Gvf = {3,{5,6,7,8}}; int x; x = Gvf.d + Gvf.or[1]; Problem 4. #define QVPZ(x,y) (((y)*(y))%(x)) Answer 4: 3 x = QVPZ(6,3); Problem 5. int i[] = {1,2,3,4,5,6,7,8,9,0}; Answer 5: 8 int x=2, *ptr = i; while ( *ptr<4 ) x += *ptr++; Problem 6. int x, a[100]={1}; Answer 6: 0 x = *(a + 1); Problem 7. #include Answer 7: 'F' #include FILE *in, *out; int x = 'f'; out = fopen("myfile", "w"); putc(toupper(x),out); fclose(out); in = fopen("myfile","r"); x = getc(in); In Problems 8 and 9, suppose that A and B are int's with A = 6 and B = -2. Determine the value of the given expression: Problem 8. B-A/B+A Answer 8: 7 Problem 9. ++A*B-- Answer 9: -14 In Problems 10 and 11 below, determine what the program prints: Problem 10. #include int ByTwo( const int x, const int q ) { return ( x%2 ) ? q : ByTwo( x/2, q+1 ); } main(void) { const int x = 28; printf("ByTwo(%d)=%d\n", x, ByTwo(x, 0) ); return 0; } Answer 10: ByTwo(28)=2 Problem 11. #include #include typedef struct Item { int Value; struct Item *Next; } *Stack; Stack Push ( int Value, Stack Old ) { Stack New; New = (Stack)malloc(sizeof(struct Item)); New->Value = Value; New->Next = Old; return New; } Stack Pop ( Stack Old ) { Stack New = 0; if(Old) { New = Old->Next; free(Old); } return New; } int TopValue( Stack Top ) { if(Top) return Top->Value; else return 0; } main(void) { int i, x; Stack S; for(i=0; i<15; i++) S = Push( i, S ); for(i=0; i<11; i++) S = Pop(S); x = TopValue(S); printf("x=%d\n", x); return 0; } Answer 11: x=3 Problem 12. Write a complete ANSI C program that (1) reads numbers from a file named ``accounts'', written one number per line, exiting if the file can't be read for any reason, (2) sums the positive numbers, (3) sums the negative numbers, (4) counts the zeroes, and (5) prints the count and the two sums with two decimal places of accuracy to standard output with identifying text. Answer 12: #include #include main(void) { FILE *input_file; float x, sum_of_positives=0, sum_of_negatives=0; int number_of_zeroes=0; input_file = fopen("accounts","r"); assert(input_file); while( fscanf(input_file, "%f", &x) != EOF ) { if(x==0) ++number_of_zeroes; else if(x>0) sum_of_positives += x; else sum_of_negatives += x; } fclose(input_file); puts("Contents of file ``accounts'':"); printf("\tNumber of zeroes: %d\n", number_of_zeroes); printf("\tSum of positives: %.2f\n", sum_of_positives); printf("\tSum of negatives: %.2f\n", sum_of_negatives); return 0; }