Write a function which, given a positive integer n, prints the nth Fibonacci number.
        f(n) = f(n - 1) + f(n - 2).      F(1) = f(2) = 1

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

int fib(int);

int main(int argc, char **argv) {
    int number;
    printf("Enter a positive integer: ");
    scanf("%d", &number);
    for (int i = 1; i <= number; i++)
        printf("%d ", fib(i));
    return 0;

int fib(int n) {

    if (n == 1 || n == 2)
        return 1;
        return fib(n-1) + fib(n-2);


When you compile and execute the above program it produces the following result on Linux:

Enter a positive integer: 6
1 1 2 3 5 8 

Brief Explanation

  • The Fibonacci numbers or Fibonacci sequence is a series of numbers in which each number (Fibonacci number) is the sum of the two preceding numbers.
  • The function fib which determines a Fibonacci number is a recursive function. A recursive function is a function which either calls itself or is in a potential cycle of function calls.
  • It returns 1 if n is 1 or 2 and calls itself if n is greater than 2.

Add comment

Security code