1

Hi I have a homework question that needs some clarifications,

1.

public int f (int n) {
    if (n < 0)
      return 2;
    else
      return f (n - 1) + f (n - 3);
  }

what is the value when the recall is f(3) I know that this loops so

f(3) = f(2)+2
     = f(1)+2+2
     = f(0)+2+2+2
     = 8

but I'm not sure if Java considers 0 less than 0.

9
  • 0 is not less than 0. Be aware that a String of length 10 has a final index position of 9 since the String indices start from 0. Commented Apr 3, 2014 at 1:47
  • Why don't you run your program and see what output you get? Commented Apr 3, 2014 at 1:47
  • 2
    0 is not less than 0. That's not even logical if you say it out loud... Commented Apr 3, 2014 at 1:47
  • @David Wallace I just started Java so I don't know how to run the program. So in other words I have to go one step further? Commented Apr 3, 2014 at 1:49
  • OK, does your computer have either Eclipse, or IntelliJ or NetBeans on it? Commented Apr 3, 2014 at 1:51

2 Answers 2

3

Java does not consider 0 less than 0.

Arrays use a zero-based numbering system, so the last index is going to be the length of the array (the initialized size, 10 in this case) minus one. This is essentially a left-shift from

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

to

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

So

names[names.length] = "Hello";

will throw an exception, as names.length will get the number of elements in the array, but will not get the last index in the array.

Sign up to request clarification or add additional context in comments.

Comments

2

0 is not less than 0. It is equal to 0. Use <= for "less than or equal to".

f(3) = f(3-1) + f(3-3)
f(3) = f(2) + f(0)

f(2) = f(2-1) + f(2-3)
f(2) = f(1) + f(-1)

f(1) = f(1-1) + f(1-3)
f(1) = f(0) + f(-2)

f(0) = f(-1) + f(-2)
f(N<0) = 2

Work your way back up.

f(0) = 2+2
f(1) = 2+2 +2
f(2) = 2+2+2 +2
f(3) = 2+2+2+2 +2+2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.