CPSC 124, Fall 2011 Quiz #3

Question 1. Explain what is meant by pseudocode, and discuss briefly how pseudocode can help you to develop an algorithm.

Answer. The term pseudocode refers to writing an informal specification or description of an algorithm, without the exact syntax or absolute completeness of an actual computer program. (Note that an algorithm written in pseudocode is still a step-by-step description of a process that can be used to solve a given task.)

Pseudocode can be used in the development of an algorithm using stepwise refinement. A very general outline of the algorithm can be written first. Then details can gradually be filled in, until an algorithm is obtained that is complete enough to be easily translated into a program.

Question 2. Write a for loop that will print out all the integers from 15 to 45 (including 15 and 45).

```    int n;
for ( n = 15; n < 46; n++ ) {
System.out.println(n);
}

OR:

int n;
for ( n = 15; n <= 45; n++ ) {
System.out.println(n);
}
```

Question 3. Show the exact output produced by the following completely useless code segment:

```    int n, k;
n = 2;
k = 2;
while (n < 10) {
n = n + k;
k++;
System.out.print(n);
if ( n % 1 == 0 ) {
System.out.print("+");
}
else {
System.out.print("-");
}
System.out.println(k);
}
```

```      4+3
7+4
11+5
```

(Each time through the loop, the computer will print the value of n, followed by either a "+" sign or a "-" sign, followed by the value of k. These will all be on a line, with no spaces, and with a carriage return at the end, since print is used for the first two outputs, and println is used for the last output. In fact, the sign will always be "+" because n%1 is always equal to 0. You can see this much just by looking at the code, before you start thinking about the values that are output. [Note: I actually meant to type n%2 in the if statement, which would have given a "+" in the first line and "-" in the next two lines.]

To determine the actual output, you have to trace the values of n and k as the code segment is executed. You might do this in a table:

```     n  |  k
---------
2  |  2    VALUES BEFORE THE LOOP
4  |  3    ===>  First output:   4+3
7  |  4    ===>  Second output:  7+4
11  |  5    ===>  Third output:   11+5
16  |  5    LOOP ENDS
```

Note that the last value of n that is printed is greater than 10, even though the loop ends when n >= 10. This is because the 11 is printed before the condition is tested. Remember that the condition is only tested at the beginning of the loop, and it cannot cause the loop to be exited in the middle, at the moment when the condition becomes false. The rest of the loop will continue after the condition becomes false. The loop only ends when the computer gets back the start of the loop and actually tests the condition.)