Welcome to the first post of the Fibonacci project. In the following weeks, I am going to write this simple program in as many languages as possible, to highlight the similarities and differences between them. Today I will start with C, a classic language that is still in use today, and a good foundation for everything else that we will see. Rather than writing a lengthy post with each language, I’ll try to comment the code to point out the important things. Hopefully, this learning experiment will teach me something, and hopefully it will provide a handy resource for people to compare languages, even if it’s in a limited capacity.
So before I started, I gave myself the following “spec sheet” for writing the code:
The purpose of the Fibonacci project is to create a simple programming example in as many languages as possible, to provide a clear demonstration of the differences and similarities between them.
The sample code should:
- Accept an input “x” (A value to progress up to)
- Starting at 0 and 1, output the Fibonacci sequence up to “x” permutations.
- There should be two functions, for clarity.
- (main) Accepts the input and calls the fibonacci function.
- (fibonacci) One that accepts the value of x and outputs the sequence.
The code should accept input from the console (stdin), with a prompt, and output to the console (stdout). This is so we keep everything simple. All of the code should be thoroughly commented.
* You'll notice that we need to include a header file that
* contains functions we need to use. Being a compiled language,
* it's inefficient to include functions that aren't needed.
* stdio.h contains functions for reading from and writing to the console
* In C, the program executes the main function. You should also take note
* that we must declare a return type for the function. In this case, it's
* an integer, and we return 0 to indicate successful completion of the
int main ()
/* Notice that we need to declare our variables, and their type */
/* printf prints a formated string to the stdout */
printf("\nHow many numbers of the sequence would you like?\n");
/* scanf reads a formated string from the stdin. We are expecting an integer here. */
/* Here we call the fibonacci function */
/* Finally, return 0 */
* This is the simple fibonacci sequence generator. Notice also, we
* declare the type of variable we expect to be passed to the function.
int fibonacci(int n)
* Here we declare and set our variables.
int a = 0;
int b = 1;
* Here is the standard for loop. This will step through, performing the code
* inside the braces until i is equal to n.
sum = a + b;
a = b;
b = sum;
So there’s my version of the Fibonacci sequence generator in C. I’m sure there are some problems with it, but the above code works. What would you change to make it better? Stay tuned for the next installment … PHP.