Example HTML page

C Program to Print the Fibonacci numbers up to a specified number

In this article, we are going to write a “C” Program to print the Fibonacci numbers up to a specified number.

What is a Fibonacci number series? Where it will start?

The Starting numbers in the Fibonacci series are 0,1. It means ‘First’ number is ‘0’, ‘Second’ number is ‘1’. These are fixed. The ‘Third’ number is the sum of the ‘First’ and ‘Second’ number.

Third = First + Second = 0+1 = 1

Now Fourth number is the sum of Third number and Second number.

Fourth = Third + Second = 1+1=2

Observe the following series,

0,1,1,2,3,5,8,13,21, 34,55,89…

The same thing is shown below.

         0         1

0+1 =1

        0           1           1

1+1 =2

        0          1          1        2

1+2 =3

        0          1          1        2         3

2+3=5

        0          1          1        2         3          5

3+5=8

        0          1          1        2         3          5        8

This process is continued..

5+8=13

13+8=21

21+13=34

        0          1          1        2         3          5        8       13        21      34

The next number is the sum of it’s previous two numbers.

For example if a user enters a number 50, the program has to print the Fibonacci series up to less than 50. If the next number is greater than 50, then your program should terminate.

#include <stdio.h>
int main()
{
    int first = 0, second = 1, next, n;

    printf("Enter a positive number: ");
    scanf("%d", &n);

    // we are printing first and second terms which are not changed
    printf("Fibonacci Series: %d, %d, ", first, second);

    next = first + second;

    while(next <= n)
    {
        printf("%d\t ",next);
        first = second;
        second = next;
        next= first + second;
    }
    
    return 0;
}
C Program for Fibonacci Series

Test Case 1

Output:

Command Prompt
Enter a positive number: 50
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
——————————–
Process exited after 2.15 seconds with return value 0
Press any key to continue . . .

Test Case 2

Output:

Command Prompt
Enter a positive number: 80
Fibonacci Series: 0, 1, 1 2 3 5 8 13 21 34 55
——————————–
Process exited after 1.87 seconds with return value 0
Press any key to continue . . .

In this Program initially, the header file <stdio.h> is included, because we are using ‘printf()’ function. We declared first and second values in this series are 0 and 1. These values are not changed. Through scanf() function, we are reading ‘n’, up to which number uyou

Example HTML page

Leave a Reply

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

Pin It on Pinterest