Mathematics 1201: Programming in C Solutions to Reading and Homework Assignment #2 Prof. Wickerhauser Chapter 2 Exercises: Exercise 4, p.45 Program ch2ex4.c: #include main(void) { int x; x = 37; printf("37 = %d(decimal), %o(octal), %x(hexadecimal)\n", x, x, x ); x = 037; printf("037 = %d(decimal), %o(octal), %x(hexadecimal)\n", x, x, x ); x = 0x37; printf("0x37 = %d(decimal), %o(octal), %x(hexadecimal)\n", x, x, x ); return 0; } Compilation: % cc ch2ex4.c Execution: % a.out 37 = 37(decimal), 45(octal), 25(hexadecimal) 037 = 31(decimal), 37(octal), 1f(hexadecimal) 0x37 = 55(decimal), 67(octal), 37(hexadecimal) Exercise 7, p.45 B = 5; C = 8; A = B++ + C++; /* Now B is 6, C is 9, and A is 5+8 = 13 */ A = B++ + ++C; /* Now B is 7, C is 10, and A is 6+10 = 16 */ A = ++B + C++; /* Now B is 8, C is 11, and A is 8+10 = 18 */ A = ++B + ++C; /* Now B is 9, C is 12, and A is 9+12 = 21 */ Exercise 12, p.45 int A, B = 5, C = 7; double X, Y = 2.8, Z = 16.8; /* 1 */ A = Y; /* Now A is 2 */ /* 2 */ A = -Y; /* Now A is -2 */ /* 3 */ X = A / B + C; /* Now X is 7, since A/B is -2/5=0 */ /* 4 */ X = A / B + (double) C; /* Now X is 7.0000000000000 */ /* 5 */ X = (double) A / B + C; /* Now X is 6.6000000000000 */ /* 6 */ A = Y - Z; /* Now A is -14 */ Exercise 17, p. 46: We assume that our integers have 16 bits. First convert from hexadecimal to binary: A = 0xC0B3 = 1100 0000 1011 0011 (base 2) B = 0x2435 = 0010 0100 0011 0101 (base 2) (a) ~A = 0011 1111 0100 1100 (base 2) = 0x3F4C /* affected by bit length of `int' */ (b) A | B = 1110 0100 1011 0111 (base 2) = 0xE4B7 (c) A & B = 0000 0000 0011 0001 (base 2) = 0x0031 (d) A ^ B = 1110 0100 1000 0110 (base 2) = 0xE486 (e) A >>2 = 0011 0000 0010 1100 (base 2) = 0x302C /* affected by sign */ (f) A <<2 = 0000 0010 1100 1100 (base 2) = 0x02CC /* affected by bit length of `int' */ (g) A<<-2 is undefined, since the right-hand argument is negative. Extra problem: /* 1 */ /* This program contains several errors. // OK /* 2 */ * Can you find them all? */ // Comment ends prematurely /* 3 */ #include // OK /* 4 */ #define Pi=3.141592653589793; // Use no `=' or `;' in #define /* 5 */ main( void ) // OK /* 6 */ { // OK /* 7 */ double x, y; // OK /* 8 */ float z; // OK /* 9 */ int i, // End this statement with `;' /* 10 */ if ( argc > 1 ) { // `argc' is undeclared. /* 11 */ printf('No Arguments!\n'); // Use `"' for strings /* 12 */ return(1); // OK /* 13 */ } // OK /* 14 */ x = z = Pi; // This crashes from bad `Pi' /* 15 */ y = x; // OK /* 16 */ printf ( "%f is zero.\n", x-y ); // OK /* 17 */ printf ( "%d is pi.\n", z ); // `z' needs `%f' /* 18 */ i = 1/Pi; // This crashes from bad `Pi' /* 19 */ i =* Pi; // This crashes from bad `Pi' /* 20 */ printf ( "%d is one.\n", i ); // OK /* 21 */ return(0) // End statements with `;' /* 22 */ } // OK