Our First Java Program
Below is our first Java program of the semester. Next to each line, write out what you think the code will do when run. This exercise is adapted from Head First Java.
For your convenience, here is the same code in Python:
Mystery
This is a function (a.k.a. method). It takes an array of integers and an integer as arguments, and returns an integer
- What mystery returns if inputArray = [3, 0, 4, 6, 3] and k = 2.
- Can you explain in English what does
mystery
do?
Extra: This is another function. It takes an array of integers and returns nothing.
Describe what mystery2 does if inputArray = [3, 0, 4, 6, 3]
Writing Your First Program
Implement fib which takes in an integer n and returns the nth Fibonacci number. You may not need to use all the lines.
The Fibonacci sequence is 0; 1; 1; 2; 3; 5; 8; 13; 21; : : :.
public static int fib(int n) {
// ...
}
Extra: Implement fib in 5 lines or fewer. Your answer must be efficient. You don’t have to make use of the parameter k in your solution.
public static int fib2(int n, int k, int f0, int f1) {
// ...
}