哔哩哔哩

disc01.pdf

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.
image.png
For your convenience, here is the same code in Python:
image.png

Mystery

This is a function (a.k.a. method). It takes an array of integers and an integer as arguments, and returns an integer
image.png

  • 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.
image.png
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; : : :.

  1. public static int fib(int n) {
  2. // ...
  3. }

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.

  1. public static int fib2(int n, int k, int f0, int f1) {
  2. // ...
  3. }

Solution

disc01sol.pdf