Fibonacci numbers (Pascal)

From LiteratePrograms

Jump to: navigation, search
Other implementations: ALGOL 68 | Alice ML | bc | C | C Plus Plus templates | dc | E | Eiffel | Erlang | Forth | FORTRAN | Haskell | Hume | Icon | Java | JavaScript | Lisp | Logo | Lua | Mercury | OCaml | occam | Oz | Pascal | PIR | PostScript | Python | Ruby | Scala | Scheme | Sed | sh | sh, iterative | Smalltalk | T-SQL | Visual Basic .NET

The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item is formed by adding the previous two. The sequence can be defined recursively by

1 \\ \end{cases} ."/>

Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist.


In this article we show two ways of calculating fibonacci numbers in Pascal.

<<Fibonacci.pas>>=
program Fibonacci;
var
  i, x, m, n : integer;
begin   {Begins the main part}
  writeln ('Enter the lenghts of the sequence');
  readln (x);
  n := 0; m:=1; {We have to initialize our sequence}
  writeln (n);  {and have the first output}
  writeln (m);
  i:=0;         {"i" is the number of the current iteration}
while i<x-2 do  {The first 2 "x's" we've already had
                 that's why we must get rid of them}
begin           {Begins the iteration loop}
  i:=i+1;
  m:=m+n; n:=m-n;
  writeln(m);
  if i=x-2 then writeln('Finished !');
                {The program has calculated everything
                 and lets us know about it}
end;            {The end of the while-do loop}
  readln;       {This is needed to have enough time
                 to read the output}
end.
Download code
Views