Learning how to print Fibonacci number in C


Fibonacci number in mathematical terms can be used for learning any programming languange. Now, we will learn how to print Fibonacci number in console using C. First thingsp, create a file called “fibonacci.c” :

At this example, we will produce fibonacci number in linear ways :

#fibonacci.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * fibonacci.c
 * Author : Yodi Aditya
 */
#include<stdio.h>

int main(void) {
    int a = 0;
    int b = 1;
    int c;
    int i;

    for(i=1;i<=20;i++) {
        if(a < 1) {
            printf("%dn%dn", a, b);
        }
        c = a + b;
        printf("%dn", c);
        a = b;
        b = c;
    }

    return 0;
}

This will print fibonacci in range(20). We can move futher by knowing how to make a function in C.

Functions in C
There are two types of function in C. Those that return value (int, char, float and another data type) and those doesn’t (void).

I will show you how to create function and recursive method in C :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * fibonacci.c
 * Author : Yodi Aditya
 */
#include<stdio.h>

int fib(int c); /* prototype */

int main(void) {
    int i;

    for(i=0;i<=20;i++) {
        printf("%dn", fib(i));
    }

    return 0;
}

int fib(int i) {
    if(i == 0) {
        return 0;
    } else if (i == 1) {
        return 1;
    } else {
        return fib(i-1) + fib(i-2);
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.