Fibonacci and C arrays- the perfect combo

New year upon us and back to the C training. Tonights mission was to output Fibonacci numbers via an array. The Fibonacci sequence is a sequence of numbers where the next number is the sum of the previous 2 numbers. Our C program uses an integer array to store the numbers in, then outputs to the screen:

#include <stdio.h>

int main(void){

	long int Fibonacci[20];
	int i;

	Fibonacci[0] = 0;
	Fibonacci[1] = 1;

	for(i = 2;i < 20;i++)
		Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1];

	for(i = 0;i < 20;i++)
		printf("%2i\t%li\n", i, Fibonacci[i]);

	return 0;
}

The output is as follows:

# cc -o fab fab.c
# ./fab
 0	0
 1	1
 2	1
 3	2
 4	3
 5	5
 6	8
 7	13
 8	21
 9	34
10	55
11	89
12	144
13	233
14	377
15	610
16	987
17	1597
18	2584
19	4181

Job done, what about in Perl? I’ve just thrown together something resembling the same thing in perl below except that i’m going up to 90, not 20:

#! /usr/bin/perl -w

use strict;
my $counter;
my @fabs = (0,1);
for ($counter = 2; $counter < 90; $counter++){
	push (@fabs, $fabs[$counter - 1] + $fabs[$counter - 2]);
}
$counter = 0;
for (@fabs){
	print "$counter\t$_\n";
	$counter++;
}

So i get the same output, except up to 90 of course. Now I’ve modified the C version to 90 as well so we can do a ‘time trial’, first the C version:

# time ./fab
...
87	679891637638612258
88	1100087778366101931
89	1779979416004714189

real	0m0.003s
user	0m0.001s
sys	0m0.001s

Now the Perl version:

# time ./fab.pl
...
87	679891637638612258
88	1100087778366101931
89	1779979416004714189

real	0m0.007s
user	0m0.003s
sys	0m0.003s

I snipped out most of the output, if you really want to know the results, type the code in yourself.

Want to know more about the Fibonacci sequence? Melvyn Bragg did one of his ‘In Our Time’ programmes about it, 45 mins of Radio 4 gold!

http://www.bbc.co.uk/programmes/b008ct2j

This entry was posted in C, Perl and tagged , , . Bookmark the permalink.

Leave a Reply