EXERCISES for Week 2 1. What is the value of j after the following code is executed? for (i = 0, j = 0; i < 10; i++) j += i; 2. What is the value of j after the following code is executed? for (i = 0, j = 1; i <= 10; i++) j += j; 3. What is the value of i after the following code is executed? for (i = 0; i < 10; i++) i += i; 4. Write a C function that takes an integer N as argument and returns the largest power of two less than or equal to N. 5. What happens when you type the command "wc" in the Unix shell? 6. What happens when you type the command "wc wc" in the Unix shell? 7. When you type the command "wc | wc", then ctrl-D, you get the following result: % wc | wc 1 3 31 Why? 8. Suppose that TOY is started at 10 with the data below loaded into memory. What is in R1 and R2 when the machine halts? 10: B111 11: B210 12: 2112 13: 0000 9. Suppose that TOY is started at 10 with the data below loaded into memory. What is in R1 and R2 when the machine halts? 10: 9111 11: 9210 12: 2112 13: 0000 10. 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 for Week 2 1. 45 2. 2048 3. 15 4. int f(int N) { int j; for (j = 1; j <= N; j += j) ; return j/2; } 5. Nothing, it waits for you to type something ("standard input"). If you type ctrl-C, you get your prompt back; if you type ctrl-D, it counts 0 lines, 0 words, and 0 characters: % wc 0 0 0 6. % wc wc wc: No such file or directory 7. The output of the first "wc" is given in 5. above. It has 1 line, 3 "words" (the 0s), and 31 characters (27 blanks, the 0s, and a newline). 8. R1 = 0001, R2 = 0010 9. R1 = 00FF, R2 = 9111 10. 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 --------------------------------------------- READING for Week 2 Notes for lectures 4-6. Sedgewick, pp. 83--84 Kernighan and Ritchie, 1.4 1.5 1.6