EXERCISES ON ARRAYS READING ------- Notes for lecture 2. Sedgewick, p. 83-84 Kernighan and Ritchie, 1.6 King, Chapter 8 (Arrays) SUPPLEMENTAL READING -------------------- Deitel and Deitel, 6.1-6.3 EXERCISES --------- 1. What happens if you declare an array with #define N 1000 int a[N]; 2. What happens if you declare an array with #define N 1000 int a[N*N]; 3. What happens if you declare an array with #define N 1000 int a[N*N*N]; 4. Explain what the following program does: #include main() { int num, i, maxi; int a[100]; for (i = 0; i < 99; i++) a[i] = 0; while (scanf("%2d", &num) != EOF) a[num]++; maxi = 0; for (i = 1; i < 99; i++) if (a[i] > a[maxi]) maxi = i; printf("%d\n", maxi); } 5. Write a program that reads a sequence of integers between 0 and 99 from standard input and prints the median value. % echo 11 9 99 34 12 18 1 | a.out 12 % echo 1 1 1 1 1 2 3 3 3 | a.out 1 % 6. What is in a[8] after the following code is executed? for (i = 0; i < 10; i++) a[i] = 9-i; for (i = 0; i < 10; i++) a[i] = a[a[i]]; . . . . . ANSWERS TO EXERCISES ON ARRAYS 1. Equivalent to a[1000]. This is a convenient way to name the size of the array at *compile* time, so we can use the name in for loops and elsewhere in the program. If we want to change the size, we only have to change it in the define line. The size is constant at *run* time: N doesn't change when the program runs. 2. Equivalent to a[1000000]. Simple expressions involving defined variables can be evaluated at *compile* time. In ancient times (10 years ago), not many computers could hold such a big array; nowadays most can. 3. Equivalent to a[1000000000]. Might work; but your computer probably can't hold such a big array. Exact behavior depends on the compiler. % more bigarray.c #include #define N 1000 main() { int i; int a[N*N*N]; for (i = 0; i < N*N*N; i++) a[i] = 0; } % cc bigarray.c % a.out Segmentation Fault (core dumped) % lcc bigarray.c bigarray.c:5: size of `array of int' exceeds 2147483647 bytes bigarray.c:8: warning: missing return value % 4. Computes the value that occurs most often in an integer sequence of values between 0 and 99 (this is called the mode, if there is only one such value). The "%2d" in the scanf format specification protects against bad input (only reads two digits), but not totally: what about negative numbers, or character strings? 5. If N is odd, this program prints the exact median. If N is even, the number of inputs that are <= the printed value is 1 greater than the number of inputs that are >= the printed value. #include main() { int num, N = 0, i, cnt = 0; int a[100]; for (i = 0; i < 99; i++) a[i] = 0; while (scanf("%2d", &num) != EOF) { N++; a[num]++; } for (i = 0; i < 100; i++, cnt += a[i]) if (cnt > N/2) break; printf("%d\n", i); } 6. 1 i: 0 1 2 3 4 5 6 7 8 9 a[i] after 1st loop: 9 8 7 6 5 4 3 2 1 0 a[i] after 2nd loop: 0 1 2 3 4 4 3 2 1 0