How to Write a Program That Generates the Fibonacci Series by Using Function

Leonardo of Pisa (aka Fibonacci) was a 13th Century Italian mathematician. He was famous during his lifetime for introducing the Hindu number system we now use into a Medieval world that was still using Roman numerals. Today, he is most famous for a series that starts 1, 1, 2, 3, 5, 8, ... and so on. After the first two ones, each new number is the sum of the last two numbers. This series pops up in several places in nature and is also helpful in solving some difficult problems. It is a common programming exercise in computer science classes.

Instructions

    • 1

      Sketch out the solution in pseodocode -- an English language description of the function. The Fibonacci function will have three parts. Part 1 takes care of the first two numbers in the sequence. The next section sets up a couple of variables, a and b, that keep track of the last two numbers in the Fibbonacci series so it is easy to find the next number in the series: a + b. The last part of the function is a loop that keeps track of finding the correct number of new elements in the series, printing each element and updating a and b.

    • 2

      Take care of a tricky problem that arises when a new number in the sequence is found and a and b are updated. If a and b are the last two numbers in the series, the next number in the series is a + b. The new a is the old b and the new b is the old a + b -- but the old a has been altered. Look what happens when a = 3 and b = 5. Replacing a with b makes a = 5, which is correct but replacing b with a + b makes b = 5 + 5 = 10 which is incorrect.

    • 3

      Write the code in the C language:

      int fibb-function(int lim){ if (lim == 1) printf ("1"); if (lim greater-than-or-equal-to 2) printf("1 1"); if (lim greater-than 2) {int a:-1; int b:=1; int count:=2; while(count less-than lim) {printf(a+b); count++; c:=a+b; a:=b; b:=c;}}}

      where lim is the number of elements of the series that are printed. The problem with updating a and b is solved by saving a + b in c, before replacing a by b and replacing b with c.

Learnify Hub © www.0685.com All Rights Reserved