# MCS-287 Homework 5 (Spring 2006)

## Due: April 10, 2006

• Exercise 4.x2: The `for` statement in languages such as Java is sufficiently general that not all four components are needed for some applications. As an example, complete the `LeftDigit.java` program shown below by filling in two of the four blanks, leaving the other two empty. The goal is that you should be able to compile and test the program as follows:

```javac LeftDigit.java
java LeftDigit 314 -314 5 -5 10 -10 0
```

```314: 3
-314: -3
5: 5
-5: -5
10: 1
-10: -1
0: 0
```

The program you are to complete follows:

```public class LeftDigit {
public static int leftDigit(int n){
for(__________; __________; __________)
__________;
return n;
}

public static void main(String[] args){
for(String arg : args)
System.out.println(arg + ": " + leftDigit(Integer.parseInt(arg)));
}
}
```
• Exercise 4.x3: Complete the `Fib.java` program shown below by filling in the contents of the `switch` statement subject to the following constraints: (1) You should use only one `return` statement. (2) You should not modify any code outside the `switch` statement. (3) Your procedure should calculate Fibonacci numbers using a tree-recursive process. You should be able to compile and test as follows:

```javac Fib.java
java Fib 0 1 2 3 4 5 6 7 8 9
```

```0: 0
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
8: 21
9: 34
```

The program you are to complete follows:

```public class Fib {
public static int fib(int n){
switch(n){

}
}

public static void main(String[] args){
for(String arg: args)
System.out.println(arg + ": " + fib(Integer.parseInt(arg)));
}
}
```
• Exercise 4.x4: The following Java program contains several different variables that are named `n`. Show your knowledge of scoping rules by renaming each of the variables to a distinct name, such as `n1`, `n2`, or `n3`, while making sure that the meaning of the program is unchanged.

```public class Scoping {
public static void main(String[] args){
int before = n, n = 42, after = n;
foo(before);
foo(after);
bar();
}
private static void foo(int n){
System.out.println(n);
}
private static void bar(){
System.out.println(n);
}
private static int n = 17;
}
```
• Exercise 4.x5: Page 111 of the textbook mentions that languages differ with regard to whether a procedure's parameters have the same scope as local variables defined in the procedure's body or whether they constitute an outer scope wrapped around the procedure body. Jay follows the example of Java in using the same scope for the parameters and the body. How would the definition of typingm on page 115 need to be changed in order to make Jay instead be like Algol 60, with the parameters bound in a distinct scope just outside the scope for the procedure body?

Course web site: http://www.gustavus.edu/+max/courses/S2006/MCS-287/
Instructor: Max Hailperin <max@gustavus.edu>