C Program To Generate Fibonacci Series using Function


Lets write a C program to generate Fibonacci Series using function / method.

Related Read:
Fibonacci Series using While loop: C Program
C Program To Generate Fibonacci Series using For Loop

What Is Fibonacci Series ?
Fibonacci Series is a series of numbers where the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Its recurrence relation is given by Fn = Fn-1 + Fn-2.

Below are a series of Fibonacci numbers(10 numbers):
0
1
1
2
3
5
8
13
21
34

How Its Formed:
0 <– First Number (n1)
1 <– Second Number (n2)
1 <– = 1 + 0 (previous two numbers)
2 <– = 1 + 1 (previous two numbers)
3 <– = 2 + 1 (previous two numbers)
5 <– = 3 + 2 (previous two numbers)
8 <– = 5 + 3 (previous two numbers)
13 <– = 8 + 5 (previous two numbers)
21 <– = 13 + 8 (previous two numbers)
34 <– = 21 + 13 (previous two numbers)

Video Tutorial: C Program To Generate Fibonacci Series using Function


[youtube https://www.youtube.com/watch?v=R3MPbqvYooA]

YouTube Link: https://www.youtube.com/watch?v=R3MPbqvYooA [Watch the Video In Full Screen.]


Source Code: C Program To Generate Fibonacci Series using Function

#include<stdio.h>

void fibonacci(int);

int main()
{
    int limit;

    printf("Enter the number of terms to be printed\n");
    scanf("%d", &limit);

    fibonacci(limit);

    return 0;
}

void fibonacci(int num)
{
    int n1 = 0, n2 = 1, n3, count;

    printf("\nFibonacci Series ..\n");
    printf("1. %d\n2. %d\n", n1, n2);

    for(count = 3; count <= num; count++)
    {
        n3 = n1 + n2;
        printf("%d. %d\n", count, n3);

        n1 = n2;
        n2 = n3;
    }
}

Output 1:
Enter the number of terms to be printed
5

Fibonacci Series ..
1. 0
2. 1
3. 1
4. 2
5. 3

Output 2:
Enter the number of terms to be printed
14

Fibonacci Series ..
1. 0
2. 1
3. 1
4. 2
5. 3
6. 5
7. 8
8. 13
9. 21
10. 34
11. 55
12. 89
13. 144
14. 233

Logic To Generate Fibonacci Series using Function

We ask the user to enter the limit i.e., how many terms in the Fibonacci series to be printed. We pass this user entered limit to function fibonacci.

Inside fibonacci function
We initialize n1 to 0 and n2 to 1 and display it to the console. We do this because we know that in any Fibonacci series the first two numbers are 0 and 1.

Now we add n1 and n2 and assign it to n3, and display the value of n3 – which is the next number in the Fibonacci series. We use for loop to keep printing the Fibonacci series until the limit entered by the user.

Note: Function fibonacci takes 1 integer type argument and doesn’t return anything, so its return type is void.

For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List

For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert

Leave a Reply

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