-- three versions of fibonacci function in Ada 95 -- to run this program on a system (linux or cygwin) with gnat ada95 installed: -- type "gnatmake fibs.adb" then "./fibs". with Text_IO, Ada.Integer_Text_IO; use Text_IO, Ada.Integer_Text_IO; with Ada.Strings.Unbounded; use Ada.Strings.Unbounded; with Ada.Float_Text_IO; use Ada.Float_Text_IO; -- Most basic Ada code segments are enclosed in begin and end. Sometimes, -- such as with function/procedure bodies, "do" or "is" or "loop" is -- used in place of "begin". They correspond to { and } in other -- languages. Every code segment is logically made up of a declaration -- segment and a body with actual code (in C++/Java declarations and -- code can be mixed, but not in Ada). -- The basic format of an Ada procedure is: -- procedure name is -- declarations ... (variables, local functions, datatypes) -- begin -- body of procedure -- end name; -- Procedures can have in (default), out and in out parameters. Functions -- may only have in parameters. In params cannot be changed. -- There's no "main" procedure but the outermost procedure (fibs here) -- should match the filename -- warning: Ada is NOT case sensitive procedure fibs is function Fib1(N : Integer) return Integer is begin if (N<2) then return 1; else return (Fib1(N-1) + Fib1(N-2)); end if; end Fib1; function Fib2(N : Integer) return Integer is -- declaring a local function within fib2: function F(N : Integer; A:Integer; B:Integer) return Integer is begin if (N<2) then return B; else return F(N-1,B,A+B); end if; end F; -- begin return F(N,1,1); end Fib2; -- in the third version, we use a while loop together with an "out" -- parameter to return the value: procedure Fib3(N:Integer; Answer : out Integer) is -- local vars: A : Integer; B : Integer; I : Integer; Temp : Integer; begin A := 1; B := 1; -- note the use of ":=" for assignment, "=" means "==" in ada I := N; while (I>1) loop Temp := B; B := A+B; A := Temp; I := I-1; end loop; Answer := B; -- puts result in out parameter end Fib3; -- another thing to note: why is the variable I needed? Why not just -- use N? Because Ada is trying to impose a stricter style of programming -- on you. You cannot change the values of "in" parameters. X, Y : Integer; -- utility vars begin -- this is the main body of fibs Put("The 5th Fibonacci number is "); Put(Fib1(5),Width=>4); New_Line; Put("With tail recursion it's also"); Put(Fib2(5),Width=>4); New_Line; Fib3(5,X); Put("Without recursion it's still "); Put(X,Width=>4); New_Line; end;