The purpose of this exercise is to practice reading code and recognizing the traversal patterns in this chapter. The following methods are hard to read, because instead of using meaningful names for each variable and method, they use names of fruits.

For each method, write a quick description of what the method does. For each variable, identify the role it plays.

public static int banana(int[] a){
int kiwi = 1;
int i = 0;
while (i<a.length){
kiwi = kiwi * a[i];
i++;
}
return kiwi;
}

public static int grapefruit(int[] a, int grape){
for (int i = 0; i < a.length; i++){
if (a[i] == grape){
return 1;
}
}
return -1;
}

Need help getting:
Banana
Grapefruit
Kiwi
Grape

Exercise 2:

What is the output of the following program? Describe in a few words what mus does.

public static int[] make(int n ){
int[] a = new int[n];
for (int i = 0; i < n; i++){
a[i] = i +1;
}
return a;
}

public static void dub(int[] jub){
for (int i = 0; i <jub.length; i++){
jub[i] *= 2;
}
}

public static int mus(int[] zoo){
int fus = 0;
for(int i =0; i<zoo.length; i++){
fus += zoo[i];
}
return fus;
}

public static void main(String[] args){
int[] bob = make(5);
dub(bob);
System.out.println(mus(bob));
}

I do know that the output of the program is 30.

2 answers

banana takes an array of integers and returns the product of all its elements.

grapefruit takes an array of integers and a second value.
It returns a 1 if the value is an element of the array, or -1 if not.

sure you can't figure out the others?
public static int banana(int[] a) {
int grape = 0;
int i = 0;
while (i < a.length) {
grape = grape + a[i];
i++;
}
return grape;
}