Using C By definition the first two numbers in the Fibonacci
Using C++:
By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two; for example, the first 6 Fibonacci numbers are 0, 1, 1, 2, 3, 5. Write a program that asks the user for a number between 5 and 11 (inclusive) and then displays that many Fibonacci numbers. YOU MUST write a function called fibonacci which is called from main as shown in the template. Note that the function adds up each of the Fibonacci numbers and returns the total to main. Add a newline every 10th output value. For example:
Solution
#include <iostream>
using namespace std;
int fibonacci(int n) //fibonacci function to compute and return the value of nth number
{
int i,fib,n1=0,n2=1;
int count =2;
cout<<n1<<\"\\t\"<<n2<<\"\\t\";
for(i=0;i<n-2;i++)
{
fib = n1 + n2;
cout<<fib<<\"\\t\";
n1 = n2;
n2 = fib;
count++;
if(count%10 == 0)
cout<<\"\ \";
if(i == n-2)
break;
}
return n1+n2;
}
int main()
{
int number,sum;
cout<<\"\ Please enter a number between 5 and 22\ \";
cin>>number;
if(number >5 && number <22)
{
sum =fibonacci(number); //call to fibonacci function
cout<<\"\ Fibonacci #\"<<number<<\" is \" <<sum;
}
else
{
cout<<\"Error: Number should be between 5 and 22\";
}
return 0;
}
output:
Success time: 0 memory: 3472 signal:0
Please enter a number between 5 and 22 23
Error: Number should be between 5 and 22
