Robson » Little Red Book » Fibonacci numbers

Chapter 3 - Question 9

In the sequence, 0 1 1 2 3 5..., the next number is obtained by adding together the previous two numbers.

Write a program that accepts a positive integer as input and generates that number of terms of the sequence.

Solution 1

PHP:

<?
   // generate a random number
   // this will be the amount of numbers that will be generated
   $number = mt_rand(2, 25);
   
   // start the sequence with zero and one
   $sequence = array(0, 1);
   
   // loop from the third number in the sequence until no more are needed
   for ($n = 2; $n < $number; $n++)
       // add the value just before and before that to the end of the array
       $sequence[] = $sequence[$n-1] + $sequence[$n-2];
 
   // show how many are going to be displayed
   echo 'First ' . $number . ' numbers of the Fibonacci sequence:<br />';
   
   // join all the parts of the sequence array together and show to the user
   echo implode(' ', $sequence);
?>

Which produces:

First 7 numbers of the Fibonacci sequence:
0 1 1 2 3 5 8

Solution 2

C++:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
   int iMax = atoi(argv[1]);
   int fibonacci[iMax];
   int iCurrent = 0, iCounter = 2;
   fibonacci[0] = 0;
   fibonacci[1] = 1;
   printf("0, 1");
   while (iCounter < iMax)
   {
       iCurrent = fibonacci[iCounter-1] + fibonacci[iCounter-2];
       fibonacci[iCounter++] = iCurrent;
       printf(", %d", iCurrent);
   }    
}

Log

© 2004-17 robson | cc unless stated