C Program To Returns the nth element of the Fibonacci sequence.

How to write a C Program To Returns the nth element of the Fibonacci sequence in C Programming Language ?


Solution For C Program :

/*C Program To Returns the nth element of the Fibonacci sequence.*/

#include <stdio.h>

/**
 * Returns the nth element of the Fibonacci sequence.
 */
int fibRecursive(unsigned int n)
{
// There is no 0th element of the Fibonacci sequence.
if (n == 0) return -1;

// Base case: 1st or 2nd elements.
if (n == 1 || n == 2) return 1;

// Otherwise, return the sum of the (n-1)th and (n-2)th elements.
return fibRecursive(n - 1) + fibRecursive(n - 2);
}

int main()
{
printf("The fibonacci sequence is:\n");
for (unsigned int n = 1; n < 20; ++n) {
printf("%d\n", fibRecursive(n));
}
printf("...\n");
return 0;
}


Learn More :