In: Computer Science
Write a c++ program of the Fibonacci Sequence. Have the user enter a positive integer n and compute the nth Fibonacci number. The program should end when the user enters a number less than or equal to zero
C++ code:
#include <iostream>
using namespace std;
//function to find fibonacci number
int fibo(int n){
//checking if n is less than or equal to 1
if(n<=1)
//returning n
return n;
else
//recursivly calling fibo function to find Fibonacci number
return fibo(n-1)+fibo(n-2);
}
int main(){
int n;
//asking for n
cout<<"Enter n: ";
//accepting it
cin>>n;
//looping till n is greater than or equal to 0
while(n>0){
//printing Fibonacci number
cout<<"Fibonacci number:
"<<fibo(n-1)<<endl;
//asking for n
cout<<"Enter n: ";
//accepting it
cin>>n;
}
return 0;
}
Screenshot:
Input and Output: