|
|
|
Chapter 6Answers to Selected Exercises
4. [was #10] (c) is not equivalent to (a) and (b), because
10. [was #12] Consider the following while ( ) { continue; } The equivalent code using while ( ) { goto loop_end; loop_end: ; /* null statement */ } 12. [was #14] for (d = 2; d * d <= n; d++) if (n % d == 0) break; The if (d * d <= n) printf("%d is divisible by %d\n", n, d); else printf("%d is prime\n", n); 14. [was #16] The problem is the semicolon at the end of the first line. If we remove it, the statement is now correct: if (n % 2 == 0) printf("n is even\n"); Answers to Selected Programming Projects2. [was #2] #include <stdio.h> int main(void) { int m, n, remainder; printf("Enter two integers: "); scanf("%d%d", &m, &n); while (n != 0) { remainder = m % n; m = n; n = remainder; } printf("Greatest common divisor: %d\n", m); return 0; } 4. [was #4] #include <stdio.h> int main(void) { float commission, value; printf("Enter value of trade: "); scanf("%f", &value); while (value != 0.0f) { if (value < 2500.00f) commission = 30.00f + .017f * value; else if (value < 6250.00f) commission = 56.00f + .0066f * value; else if (value < 20000.00f) commission = 76.00f + .0034f * value; else if (value < 50000.00f) commission = 100.00f + .0022f * value; else if (value < 500000.00f) commission = 155.00f + .0011f * value; else commission = 255.00f + .0009f * value; if (commission < 39.00f) commission = 39.00f; printf("Commission: $%.2f\n\n", commission); printf("Enter value of trade: "); scanf("%f", &value); } return 0; } 6. [was #6] #include <stdio.h> int main(void) { int i, n; printf("Enter limit on maximum square: "); scanf("%d", &n); for (i = 2; i * i <= n; i += 2) printf("%d\n", i * i); return 0; } 8. [was #8] #include <stdio.h> int main(void) { int i, n, start_day; printf("Enter number of days in month: "); scanf("%d", &n); printf("Enter starting day of the week (1=Sun, 7=Sat): "); scanf("%d", &start_day); /* print any leading "blank dates" */ for (i = 1; i < start_day; i++) printf(" "); /* now print the calendar */ for (i = 1; i <= n; i++) { printf("%3d", i); if ((start_day + i - 1) % 7 == 0) printf("\n"); } return 0; } Copyright © 2008, 1996 W. W. Norton & Company, Inc. All rights reserved. |