You're online now.

Hurray! you are online now.

Write a C program to calculate the nth number in the Fibonacci series using recursion

The program calculates the nth number in the Fibonaccci series using recursion.

#include<stdio.h>
    int fibonacci(int n){
        if(n == 0 || n == 1){
            return n;
        }
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
    int main(){
        int n;
        printf("Enter the number : "); 
        scanf("%d", &n);
        printf("%d", fibonacci(n));
        return 0;
    }
#include<stdio.h>

Includes <stdio.h> the standard library for using the input/output inbuild operation.

int fibonacci(int n){
        if(n == 0 || n == 1){
            return n;
        }
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

The function calculate the nth Fibonacci number using recursion. ‘n’ the input parameter to the function ‘fibonacci()’, which represents the index of the Fibonacci number to be calculated. For example, if ‘n’ is 5, the function will calculate the 5th Fibonacci number (which is 5). return the nth number in the Fibonacci sequence.

int main(){
    	int n;
    	printf("Enter the number : ");
    	scanf("%d", &n);
    	printf("%d", fibonacci(n));
    	return 0;
    }

The program prompts the user to enter a number and then prints the last number in the fibonacci series up to that number. The maiin function is returning an integer value of 0, which indicates that the program has executed successfully.

Algorithm

1. Start
2. Declared n as integer
3. Read the input froom the user
4. Display the last fibonacci series return by the function of fibonacci()
5. End

Pseudocode

1. INCLUDE stdio.h
2. FUNCTION fibonacci(int n)
    1. IF n == 0 or n == 1
        RETURN n;
    2. RETURN fibonacci(n - 1) + fibonacci(n - 2)
3. FUNCTION main()
    1. DECLARED n AS INTEGER
    2. PRINT "Enter the number"
    3. READ n FROM USER
    4. PRINT "%d", fibonacci(n)
    5. RETURN 0
🖤 0
Buy me coffee ☕

Comments

Oops!

No comments here...