Exercise: Fibonacci Sequence

Very often the for loop is used when you need to execute some code exactly N times–in other words, it's very easy to count iterations using for:

for (i = 0; i < N; ++i) {
	// code
}

Note: you could've written for (i = 1; i <= N; ++i) and it would've been the same number of iterations, just starting from 1 to N inclusive, but we normally start indexing with 0; you will understand why we prefer it when we start talking about arrays a little bit later.

Let's apply what you learned and write the code that prints the first 30 numbers of the Fibonacci sequence which goes like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, ... – the first two numbers are 0 and 1, and each of the following numbers is the sum of the two preceding numbers:

Do you have an idea how to write this code? Do it, and make sure the test passes! If you are stuck, I'll give you some hints below.

#include <stdio.h>

int main() {

	/* print one number in each line:  printf("%d\n", a); */

	return 0;
}

To solve this problem, you will need at least three variables, and maybe four. One of them, let's call it i, will be a loop iteration counter. The other two, let's say, a and b, will store the previous two numbers. I'll also add c just in case, we'll use it later.

int a, b, c, i;

Assign a and b to 0 and 1 at the start of the program:

a = 0;
b = 1;

Those are the first two numbers of the sequence.

Now, how to calculate the next one? The next is a + b, and we need to save it in another variable, like this:

c = a + b;

If a is 0 and b is 1, c becomes 1.

Then you need to move to the next pair of numbers, assigning the old value of b to a, and the value of c to b:

a = b;  /* a becomes 1 */
b = c;  /* b becomes 1 but it's the "next" 1 */

So now a is 1 and b is 1, so we moved from the first and the second numbers to the second and the third. Next time you assign c, it will get assigned to 2.

And now repeat this 29 more times! You can use the for loop to make the code executed 30 times:

for (i = 0; i < 30; ++i) {
	...
}

Try putting this all together, and don't forget the important part: you need to print numbers! The easiest thing to do is to do printf("%d\n", a); on each loop iteration.

Whenever you are done with the loop, try to write the same code but avoid using the fourth variable, c. It's totally possible to use just a, b, and i!

Still stuck? Feel free to contact me if you have questions!