C program to find nth fibonacci number

C program to find nth fibonacci number

In this program, we are going to find out the nth Fibonacci number. So let’s start!

For example-

Input

First, we take input from the user to suppose we take 12

Logic-

|Basically to find out the Fibonacci number, there is one formula to calculate these and the formula is:

Fn = Fn-1 + Fn-2

Output –

According to our input, we take the output as

Enter a number: 12

The 12th Fibonacci number is 144

// C program to find nth fibonacci number.

#include <stdio.h>

long fibonacci(int num)
{
if (num <= 1)
return num;
return fibonacci(num – 1) + fibonacci(num – 2);
}

int main()
{
int num;
printf(“Enter a number: “);
scanf(“%d”, &num);

printf(“nThe %dth fibonacci number is %ld”, num, fibonacci(num));
return 0;
}

Output

Enter a number: 12

The 12th Fibonacci number is 144

Steps to find out the nth Fibonacci number:

Step 1: Create a user-defined function.

Step 2: Apply the formula to find out the nth Fibonacci number

Fn = Fn-1 + Fn-2

Step 3: Create the main function

Step 4: Get a number from the user.

Step 5: return the value to the function.

Step 6: Execute the program.

So In this way, we simply calculate the nth Fibonacci number using the function. I hope this concept is clear to you. You can also explore these concepts by using another number.

Keep learning, and keep exploring!