Problem Write a function that computes the value of the nth
Problem
Write a function that computes the value of the n-th element of the Fibonacci sequence. The function needs to call itself, in order to compute the result, i.e. it works recursively.
Use that function to create a program that asks the user to enter the number of the element of the sequence and that outputs the result on the command line.
-Steps to take:
Identify and document the input(s) and the output(s)
Describe the algorithm that solves the problem
Write the C program that solves the problem
Solution
#include <stdio.h>
#include<stdlib.h>
/*
Input : Number of elements required in the fibonacci sequence.
Output : Fibonacci sequence of required number of elements using function which generates nth
fibonacci number.
*/
/*
Algo:
Input the number from the user
Implement the fibo(n) function that returns nth number in fibonacci sequence.
From 0 to number generate fiboncci sequence using fibo(n)
*/
//Function which generates nth fibonacci number in a sequence.
int fibo(int n)
{
//if n is zero then return 0
if(n==0)
return 0;
// if n is 1 or 2 return first 2 element of fibonacci which is 1
if(n>=1 && n<=2)
return 1;
//Else calculate the current fibonacci number using previous 2 elements.
else
return fibo(n-1)+fibo(n-2);
}
int main(void) {
// your code goes here
int number,i;
//Input the number of element from user
printf(\"Enter the required number of elements of Fibonacci sequence : \");
scanf(\"%d\",&number);
//Generate the fibonacci sequence using fibo(n) function
printf(\"Fibonacci Sequence is : \");
for(i=0;i<=number;i++)
{
printf(\"%d \",fibo(i));
}
return 0;
}
OUTPUT:
Enter the required number of elements of Fibonacci sequence : 10
Fibonacci Sequence is : 0 1 1 2 3 5 8 13 21 34 55

