Homework 6: Due Friday March 25, 2011


Control structures

1. In the following pseudocode segment, assume that all variables are of type integer and that j has been assigned a value. Rewrite the segment using an equivalent loop structure in

a) Ruby

b) Any other programming language

   i = (j + 15) / 25
loop:
  if i > 10 then goto end
  i = i + 1
  j = 3 * i - 4
  goto loop
end: ...

2. Rewrite the following pseudocode segment using a multiple-selection statement in

a) Ruby

b) Any other programming language

if ((j == 1) || (j == 2)) k = 3 * j - 1
if ((j == 3) || (j == 5)) k = 2 * j + 1

if ((j == 4)) k = j + 4
if ((j == 6) || (j == 7) || (j == 8)) k = 6 * j - 7

Parameters

3. Show the contents of the variables i and arr after execution of the following program segment for each of the parameter passing methods given:

procedure f (x, y, z)
  x := x + 1
  y := z
  z := z + 1
end;

i := 1;
arr[1] := 10;
arr[2] := 11

f (i, a[i], i)

a) Pass by value

b) Pass by reference

c) Pass by value/result

d) Pass by name

Exception handling

4. Write a program in Java that inputs int values in the range -1000 to 1000 inclusive, and computes the sum of the squares. Use a Scanner object for reading the int values. The program must use exception handling for each of the following situations:

a) Any input values that are not properly formed integers or are not in the specified range should be discarded with an appropriate message displayed.
b) If an overflow occurs because the sum of squares becomes larger than a standard
int can store, print an error message and terminate the program.
c) Detect end-of-file and use it to use it to end input and cause the result to be output. (In Windows, Ctrl-Z generates an end-of-file condition for keyboard input.)