In: Computer Science
There are many applications of the Fibonacci series both in mathematics and in the real world. The Fibonacci series is obtained by starting with 0 and 1, and each subsequent term in the series is obtained by adding the previous two terms. Given n in the top row of the table below, the numbers in the second row represent Fib(n), the numbers in the Fibonacci series. So Fib(0) = 0, and Fib(1) = 1. Then Fib(2)is obtained by adding Fib(0)and Fib(1), or 0 + 1 = 1. n 0 1 2 3 4 5 6 7 8 9 10 Fib(n)0 1 1 2 3 5 8 13 21 34 55 Write a program for each value of n, print the Fibonacci terms that add up to it. Let the user input a single positive number n (0 < n < 1000). Error check input size. The Fibonacci terms shall be in descending order and not use two successive terms in the Fibonacci series. Finally, the program should ask if the user wants to run the program again (Check case). Use either recursion or iteration to solve this problem. Refer to the sample output below.Sample Run: Enter n: 1716 = 13 + 3 + 1Run again (Y/N): yEnter n: 5353 = 34 + 13 + 5 + 1Run again (Y/N): yEnter n: 9292 = 89 + 3Run again (Y/N): NName the program: FiboTermsXX.java or FiboTermsXX.cpp, where XX are your initials
Here is the code:
# include <iostream>
using namespace std;
//function to convert to lower case
char toLower(char c) {
//if upper case, then subtract A and add a
//to get lowercase
if (c <= 'Z' && c >= 'A') return c - 'A' + 'a';
return c;
}
int main() {
//calculate the Fibonacci numbers first
//note that at most Fib(20) is needed for
//n upto 1000
int Fib[21];
Fib[0] = 0;
Fib[1] = 1;
for (int i=2; i<21; i++) {
Fib[i] = Fib[i-1] + Fib[i-2];
}
int n;
//take input till user says no
while (true) {
cout << "Enter n: ";
cin >> n;
//ask again if out of range
while (n < 1 || n >= 1000) {
cout << "Please enter a number more than 0 and less than
1000" << endl;
cout << "Enter n: ";
cin >> n;
}
//use the Fib array to get the required sum
cout << n << " = ";
for (int i=20; i>0 && n>0; i--) {
//if Fib(i) is at most n
if (Fib[i] <= n) {
//then use it for the sum
cout << Fib[i];
n -= Fib[i];
//if n is still more than 0, then more terms are needed
if (n > 0) cout << " + ";
}
}
cout << endl;
//check if user wants another input
char yN;
cout << "Run again(Y/N): ";
cin >> yN;
//convert to lower case
yN = toLower(yN);
if (yN == 'n') break;
}
return 0;
}
Here is a screenshot of the code:
Here is a screenshot of the output of the code:
Comment in case of any doubts.