C PROGRAMMING using return statements and functions By defin
C++ PROGRAMMING (using return statements and functions)
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 22 (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 last one to main. Add a newline every 10th output value. For example:
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
// YOUR CODE GOES HERE
int main()
{
int num;
int fibb;
cout << \"Please enter a number between 5 and 22: \";
cin >> num;
cout << num << endl;
if ((num < 5) || (num > 22))
cout << \"Please follow the directions!\" << endl;
else {
fibb = fibonacci(num);
cout << endl;
cout << \"Fibonacci # \" << num << \" is \" << fibb << endl;
}
}
Solution
//code has been tested on gcc compiler
#include <iostream>
#include <string>
#include <iomanip>
#include <math.h>
using namespace std;
// YOUR CODE GOES HERE
int fibonacci(int n) //fibnoacci function
{int fib[n]; //array of size n for storing fibnoacci series
fib[0]=0;fib[1]=1; //o and 1 element is 0 and 1 respectively
int total=fib[0]+fib[1]; //total variable for storing sum of the series
for(int i=2;i<n;i++) //loop from 2 to n
{ fib[i]=fib[i-2]+fib[i-1]; //each term is the sum of previous 2 terms
total=total+fib[i]; //calculating total
}
for(int i=0;i<n;i++) //loop for printing purpose
{
if(i%10 != 0) //checking whether output is the 10th one or not
cout<<fib[i]<<\" \";
else
cout<<endl<<fib[i]<<\" \";
}
return total;
}
//Added Code ends here
int main()
{
int num;
int fibb;
cout << \"Please enter a number between 5 and 22: \";
cin >> num;
cout << num << endl;
if ((num < 5) || (num > 22))
cout << \"Please follow the directions!\" << endl;
else {
fibb = fibonacci(num);
cout << endl;
cout << \"Fibonacci # \" << num << \" is \" << fibb << endl;
}
}
**********OUTPUT***********
Please enter a number between 5 and 22: 12
12
0 1 1 2 3 5 8 13 21 34
55 89
Fibonacci # 12 is 232
**********OUTPUT***********
Note:The sum must be 232 not 144,you can add the terms and see,please let me know in case of any question,Thanks

