C ProgrammingPrint the Fibonacci series until a given number using C programming

Print the Fibonacci series until a given number using C programming

Fibonacci Series in C programming

In this tutorial, we will learn how to print the Fibonacci series in C programming. Here we will take input from the user as to which number the user wants to print the Fibonacci series. Suppose the user gives 1000, we will print the Fibonacci series until 1000. So let’s start

What is the Fibonacci series?

Now we will talk about this in two lines. Where this series is first and second numbers start with 1 and the third number is the sum of the previous two numbers. We will just increase this series by the sum of the previous two numbers.


How to print Pascal’s triangle in C programming | Pascal Pyramid


Fibonacci series in C programming

#include<stdio.h>
int main()
{

    int num1=1, num2=1, num3,i, last;
    printf("Enter the last number of fibonacci series:");
    scanf("%d",&last);
    printf(" %d", num1);
    printf(" %d", num2);
    for(i=0; i<=last; i++)
    {
        num3=num1+num2;
        if (num3>=last)
        {
            break;
        }
        printf(" %d ", num3);
        num1=num2;
        num2=num3;
    }
}

Fibonacci series Output

Code Explanation

In this programming, At first, we declared 5 variables. We initialized num1 and num2 variables with 1. Then we take input from the user and stored this value in the last variable.

Then we print num1 and num2 variables. After that, we start a for loop and stop this for a loop until the last number. Inside the for loop, we are doing the sum in our previous two numbers and storing the sum in num3 variables. Now we check if num3 is less than or equal to our last number. If our condition is true then we print num3 variables . Otherwise, we break the for loop.

At last, we swap our previous numbers. We stored the num2 variable value in num1 and num3 variable value in num2 variable. In this way, this loop works until the last number. When this loop meets the last number it will stop working.

I hope you understood this program. Stay tuned for the next program.

Tech Tutor pro
Tech Tutor pro
My name is Rasel. I am an expert in Roku streaming sticks, Roku TV, Roku channel guides. I will share my independent guide about the Roku device's Roku channel on this website.

RELATED ARTICLES