Exercise in Recursion
Your fourth Outside Assignment is to write, using recursion, a function specified by
function Fib(N : in Positive) return Positive;
Fibonacci was a mathematician in the Middle Ages. The so-called Fibonacci Series is a series of integers.&mnsp; Each number in the series is the sum of the two previous numbers. The first two Fibonacci numbers are 1.
N: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 ... Fib(N): 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ...
Note that if N = 1 or N = 2, then Fib(N) = 1; otherwise, Fib(N) = Fib(N - 1) + Fib(N - 2). Writing this function in Ada will be an easy and short assignment. A test driver is provided in FIBTEST.ADA; a listing is on page 15 of your printed course notes. As before, if all tests are passed, it displays "Congratulations, you completed the assignment!" If there's an error, it displays the test case, the answer from your function, and the right answer.
A dummy solution is in FIB.DUM. As before, you shouldn't change the lines highlighted here:
-- Dummy solution to Outside Assignment 4separate (Fibtest) function Fib(N : in Positive) return Positive is beginreturn 4;end Fib;
The steps to follow for Outside Assignment 4 are similar to those of the last two Outside Assignments. They're in your printed course notes on page 16:
- Copy FIB.DUM to FIB.ADA to make a copy of the dummy solution. Also, compile the test driver FIBTEST.ADA. You need do this step only once.
- Edit FIB.ADA to become your real solution. You may skip this step the first time through, to see error messages from the test driver.
- Compile FIB.ADA. If the compiler finds errors, go back to step 2.
- Link with the name of the main program Fibtest. Then execute. If the test driver displays error messages, go back to step 2.
- When the message "Congratulations, you completed the assignment!" is displayed, you'll have a chance to compare your solution with ours.
Please exit AdaTutor temporarily, and try Outside Assignment 4. Work at your own pace; there's no deadline. Good luck!
Congratulations on Completing Outside Assignment 4!Our solution to Outside Assignment 4 (in FIB.ANS):
separate (Fibtest) function Fib(N : in Positive) return Positive is Answer : Positive := 1; begin if N > 2 then Answer := Fib(N - 1) + Fib(N - 2); end if; return Answer; end Fib;
Your solution is probably quite similar to ours. Perhaps you used else and didn't initialize Answer in the declarative region. Perhaps you had some other minor variation. Our solution is probably no "better" than yours, if the test driver said, "Congratulations, you completed the assignment!"
Was this assignment too easy? We promise that Outside Assignment 5 will be much more challenging! But first we need to discuss procedures and functions in more detail, as well as packages and information hiding, access types, and exceptions.