Sonoma State University
Department of Computer Science
CS-370: Software Design and Development
Exercise 21: Defensive programming

Objective:

To refactor the software in a function definition defensively.

Fibonacci algorithm:

The Fibonacci sequence is a recursive algorithm. Classically, the Fibonacci is defined as:

F0 = 0

F1 = 1

Fn = Fn-1 + Fn-2

Note: n >= 0

Fibonacci algorithm implementation:

The Fibonacci sequence can be implemented in the C programming language as:

int Fibonacci (int n)
{
  if (n == 0) return 0;
  if (n == 1) return 1;
  return Fibonacci (n - 1) + Fibonacci (n - 2);
}

Exercise:

  • The Fibonacci function (above) is not very robust. For example, when the Fibonacci function is called with Fibonacci (-1), the program will recursively call itself until the stack runs out of memory and the program halts.
  • Rewrite the code section above defensively to alleviate such situations.
  • Do you see any other limitations which could cause this program function to fail? Explain.

Uploading your solution:

  • This is an individual exercise, not a team exercise.
  • Please upload your answer in either PDF (Acrobat), Word (doc/docx), or as a text file.