Solution for Exercise 11-4
ex1104
#include <stdio.h> int main() { int d; d = -10; while(d<10) { printf("%d ",d); d++; } while(d>=-10) { printf("%d ",d); d--; } putchar('\n'); return(0); }
Output
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10
9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10
Notes
* The output is generated on one line, though I've wrapped it above to better fit on this page.
* As with the solution for Exercise 11-3, the first while loop's condition stops short of the value 10. That's because variable d
equals 10 when the loop is finished. The second while loop takes advantage of that starting condition by not having to initialize variable d
.
* The increment operator is used at Line 11; the decrement operator at Line 16.
* You could have coded the second while loop as:
This change still works, and the output is the same, but it makes the code a little less readable. The goal was to display values between -10 and 10. Tossing an 11 in there might be confusing.
Copyright © 1997-2024 by QPBC.
All rights reserved