Solutions to Homework Assignment #5
1. Let S_{i} be a statement and C_{i} be a condition. i, j, k, kind are integer variables. For each of the following statements, draw a flowchart using the basic oneentryoneexit control structures.
(a) if (C_{1})
if (C_{2})
for (i = 0; i<100; i++) S_{1};
else
for (j = 100; j>0; j) S_{2};
else
for (k = 0; k<i+j; k++) S_{3};
(b) do {
while (C_{1}) S_{1};
S_{2};
} while (C_{2});
¡@
(c) switch (kind) {
case 1: {
while (C_{1}) {S_{1}; S_{2};}
break;
}
case 2: {
for (i=0; i<100; i+=kind) S_{3};
break;
}
case 3:
do {S_{4};} while (C_{2});
}
2. Consider the following program segment:
int a[5][4][3]; ¡@ for (i=0; i<5; i++) for (j=0; j<4; j++) for (k=0; k<3; k++) a[i][j][k] = i + j + k; 
Suppose the starting address of array a[0][0][0] is 0X22FEF0. Write the value or address of each of the following expressions. Explain your answers.
(a) a+2 = the address of a[2][0][0] = 0X22FEF0 + 0X60 = 0X22FF50
(b) *(a+2)+3 = the address of a[2][3][0] = 0X22FEF0 + 0X84 = 0X22FF74
(c) **(a+3)+1 = the address of a[3][0][1] = 0X22FEF0 + 0X94 = 0X22FF84
(d) *(*(a+3)+1)+1 = the address of a[3][1][1] = 0X22FEF0 + 0XA0 = 0X22FF90
(e) *(*(*(a+4)+3)+2) = the value of a[4][3][2] = 9
3. For each of the following program segments, answer how many loop iterations are executed. Explain your answers.
(a)
for (i=0; i<100; i=i+3) for (j=i; j>=0; j) { a = a + i + j; } 
The loop variable i of outer loop has values 0, 3, 6, ¼, and up to 99. The inner loop takes i+1 iterations. The total number of iterations executed by the two loops is:
The loop has a total of 1717 iterations.
(b)
i= 100; j = 10; k = 15; while (i>=j+k) { i = i  4; j = j + 3; k = k  5; } 
We can modify the above program to add a temporary variable temp as j+k:
i= 100; j = 10; k = 15; temp = 25 while (itemp>=0) { i = i  4; j = j + 3; k = k  5; temp = temp  2; } 
The initial value of itemp is 75 and, the value itemp is decremented by 2. Hence, the values of itemp are 75, 73, 71, ¼, and down to 1. The loop has a total of 38 iterations.
(c)
i = 500; j = 300; do { if (i<j) {i++; j;} else {i; j++;} } while (i!=j); 
In this program segment, i is greater than or equal to j, therefore, only the else clause of the conditional statement is executed. The value of ij is 200 initially and it is decremented by two after each iteration. Hence, it takes 100 iterations to make the loop condition i!=j become false.
4. For the following restaurant order procedure, (a) draw a flowchart to show the procedure, (b) modify the flowchart of (a) using only the basic oneentryoneexit control structures.
1. Ask and read waiter's name.
2. Ask and read table number.
3. Show the menu.
4. Select an item.
5. If the item selected is between 1 and 8, then enter the number of the
selected item.
6. Record the order and go to Step 3.
7. If the item selected in Step 4 is 0, then complete the order.
8. List all items ordered and their quantity.
9. List the total price.
10. List the waiter's name and the table number.
(a) 

(b) 
