-
How to be a C programmer - part 4
Ok, that's for the very, very basics. Let's do something a bit more complicated. The following program does compute the first 10 Fibonacci numbers. I must admit I didn't compile this so minor errors are a possibility. ( I writing from a cyber cafe so compiling here is not practical.)
------------------------------------------------------------------------------------------
#include "stdio.h"
// text after these two forward slashes means comment
// the compiler ignores everything on the line
/*
everything inside those symbols
means comment too
*/
int fibonacci (int n);
void main( ){
int i = 1;
int j = 0;
while( i < 11){
j = fibonacci(i);
printf("Fibonacci number %d is %d\n", i, j);
i = i + 1;
}
}
// program to be continued in part 5
-
How to be a C programmer - part 5
int fibonacci(int n){
if ( n <= 0){
return -1;
//-1 means ERROR
}
if(n == 1 || n == 2){
return 1;
}
int prev = 1;
int pprev = 1;
int tmp = 1;
n = n - 2;
while(n){
tmp = pprev;
pprev = prev;
prev = prev + tmp;
n = n - 1;
}
return prev;
}
----------------------------------------------------------------------------
That's a whole lot of stuff so let's comment a small bit. At the very top I wrote:
int fibonacci( int n);
That's called the prototype. That's to make the compiler aware that this function will be used during the program. The compiler reads the file from top to bottom. If it finds the function first in the main function it will raise an error and say ' I don't know about that function' or something to that effect.
int i = 0;
That means reserve a bit of memory and call it ' i ' and set it to zero. The first word is the type 'int' as in 'integer' means we are going to use ' i ' for whole numbers only.
Ok so that was a fair bit for today. I will write more tomorrow. Just in case you didn't know the fibonacci sequence is a series of numbers where the next number is the sum of the two previous. It goes:
1 1 2 3 5 8 etc.
Cheers
Gregg
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
Bookmarks