C program to find fibonacci series upto n terms

Write a C program to print Fibonacci series upto n terms using loop. How to generate fibonacci series up to n terms using loops in C programming. Generating fibonacci series up to n terms in C program.

Example:
Input upper limit: 10
Output: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Fibonacci series in C


Required knowledge

Basic C programming, While loop

Fibonacci series

Fibonacci series is a series of numbers where the current number is the sum of previous two terms.
For Example: 0, 1, 1, 2, 3, 5, 8, 13, 21...

Fibonacci series algorithm

If you look to the given series very carefully you will find a specific pattern i.e. the current number is the sum of previous two numbers.
Fibonacci series : 0, 1, 1, 2, 3, 5, 8, 13, 21...
1 is the sum of 0 + 1
2 is the sum of 1 + 1
3 is the sum of 2 + 1
5 is the sum of 3 + 2
and so on....

Lets suppose the first number as a i.e. a = 0
Second number as b i.e. b = 1
And lets suppose c as our current number in Fibonacci series also initialize the value with 0 i.e. c = 0

Now Fibonacci series algorithm is simple and contains only four steps.
Step 1: Print the value of c.
Step 2: a = b.
Step 3: b = c.
Step 4: c = a + b.

Read more interesting facts about Fibonacci series.

Program to print fibonacci series

/**
 * C program to print Fibonacci series up to n terms
 */

#include <stdio.h>

int main()
{
    int a, b, c, i, n;

    /*
     * Reads a number from user
     */
    printf("Enter value of n to print Fibonacci series : ");
    scanf("%d", &n);


    a = 0;
    b = 1;
    c = 0;

    for(i=1; i<=n; i++)
    {
        printf("%d, ", c);

        a=b;
        b=c;
        c=a+b;
    }

    return 0;
} 

Advance your skills by learning the program using recursive approach - C program to find fibonacci series using recursion.

Output
Enter value of n to print Fibonacci series : 10
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment