Problem 9: Generate the Fibonacci sequence. Starting with 0, 1 add them up then take the result and add it to the last number and repeat.
0 1 1 2 3 5 8 13 21......
Solution: Problem 7 and 8 were too hard for beginners. You can ignore those 2 problems if you want. But this is not such kind problem. lets we start..
our first number is: 0 , let, int first_num = 0;
our Second number is: 1, let, int second_num = 1;
which is our next one ? it's very easy:
int next_num = first_num + second_num = 0 + 1 = 1;
So far we get: 0 1 1
please observe the code carefully:
#include<stdio.h>
int fibo() {
int first_num = 0;
int second_num = 1;
int next_num;
int i;
printf("0 1 ");
for(i = 0; i<20; i++) {
next_num = first_num + second_num;
printf("%d ",next_num);
first_num = second_num;
second_num = next_num;
}
}
int main() {
fibo();
return 0;
}
|
above program prints first few Fibonacci numbers.
first time:
next_num = first_num + second_num = 0 + 1 = 2
first_num = second num i.e first_num = 1
second_num = next_num = 2
second time:
next_num = first_num + second_num = 1 + 2 = 3
first_num = second num i.e first_num = 2
second_num = next_num = 3
Next time:
next_num = first_num + second_num = 2 + 3 = 5
first_num = second num i.e first_num = 3
second_num = next_num = 5
.....
I think you get it. If not , debug the program or send me a mail.
Back to Problem list