Exercises 2.10 Programming Exercises
1.
Enter the program in Listing 2.9.2 and test it. Use Exercises 2.6 to test the program.
2.
Using the program in Listing 2.9.2, how many bits are in the largest unsigned integer that is supported by this program?
3.
Modify the last printf
statement in the program in Listing 2.9.2 so that the hexadecimal value is displayed in signed integer format. What is the largest integer you can enter in hexadecimal while still getting “correct” output?
printf("%#010x represents the unsigned decimal integer %d\n", bitPattern, bitPattern);
Any integer greater than \(\hex{7fffffff}\) gives a negative output. This will be explained in Section 3.4, but for now realize that this change is caused by printf
formatting, not the storage format, which is still unsigned int
. Also note that we did not change scanf
's reading format.
4.
Modify the program in Listing 2.9.2 so that it also displays the addresses of the x
and y
variables. The addresses should be displayed in hexadecimal. How many bytes does the compiler allocate for each of the int
s?
The printf
formatting code to display an address is %p
.
/* echoDecHexAddr.c * Prompts user to enter a number in decimal, another in * hexadecimal then echoes both in both bases, also showing * where values are stored. * 2017-09-29: Bob Plantz */ #include <stdio.h> int main(void) { int x; unsigned int y; while(1) // loop "forever" { printf("Enter a decimal integer (0 to quit): "); scanf("%i", &x); if (x == 0) break; // break out of loop printf("Enter a bit pattern in hexadecimal: "); scanf("%x", &y); if (y == 0) break; // break out of loop printf("%i is stored as %#010x at %p, and\n", x, x, &x); printf("%#010x represents the decimal integer %d stored at %p\n\n", y, y, &y); } printf("End of program.\n"); return 0; }
Notice the use of an “infinite” loop and a break
statement to end a program.