Recursion Examples

The following function getInteger prompts the user for a positive integer and validates the users input.
Return the users valid input or recursively ask again for a valid value.
public int getInteger() { int ret = -1; System.out.print("Enter a positive integer: "); Scanner keyboard = new Scanner(System.in); ret = keyboard.nextInt(); if (ret <= 0) { System.out.println("Input must be positive."); System.out.println("Pleae Try again.\n"); getInteger();//try again } return ret; }
getInteger was called from the main progam in testi.java
Here is a sample program run :

The user is prompted until a positive number is entered. Why does the program show that the value returned is -13?
What would fix the problem. See the fix.


The Fibonacci Sequence
The Fibonacci Sequence is the series of numbers that begin with:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
The next number is the sequence is found by adding the two numbers before it.
So the next numer in the sequence would be (55 + 34) = 89.
The Fibonacci Sequeces has a recursive definition such that the n'th Fibonocci number
f(n) = f(n - 1) + f(n - 2)
A method to find the n'th Fibonacci number is provided below; the main program prompts the user for a positive number of Finbonacci numbers to print out.
    Some variation may exist as to what the first number in the sequence should be, here is who this program will define the sequence:
  • f(0) = 0, there really isn't a 0'th of anything when you think about it
  • f(1) = 1
  • f(2) = 1, either by definition of f(1) + f(0)
  • f(3) = f(2) + f(1) = 2
  • f(n) = f(n - 1) + f(n - 2)

public int fib(int n) { if (n < 0) return -1; // n is not valid if (n == 0) return(0); if (n == 1) return(1); if (n == 2) return(1); if (n > 2) return fib(n - 2) + fib(n - 1); return -1; // no way to get here }
getInteger was called from the main program to get the number of Fibonacci numbers to print, and then called fibwas called for each value 1..number specified
Here is a sample program run :


The following function fixed version of getIntegerprompts the user for a positive integer and validates the users input.
Return the users valid input or recursively ask again for a valid value. In the origninal function, when the function was called recursively the return value was not saved; so when the user entered -13 the only value or ret was -13 and -13 was returned. The fix is to assign ret the returned value of the recursive call of getInteger>.
public int getInteger() { int ret = -1; System.out.print("Enter a positive integer: "); Scanner keyboard = new Scanner(System.in); ret = keyboard.nextInt(); if (ret <= 0) { System.out.println("Input must be positive."); System.out.println("Please Try again.\n"); ret = getInteger();//try again } return ret; }
This is the orignial output from the main program calling getInteger.

This is the orignial output from the main program calling FIXED getInteger. (also the spelling of Please was corrected)