Okay, so for a project I'm doing, I'm supposed to print the nth term of the fibonacci series and the series up to that number depending on what they user inputs. I don't really know how to make it print the series up to the number the user inputs, but here is what I have.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main() {
int remember;
int num1 = 1;
int num2 = 1;
int math = 0;
int many= 0;
cin >> many;
for(int i=0; i<many; i++){
remember = num1;
math = num1 + num2;
num1 = num2;
num2 = math;
}
cout << remember << " ";
}
I'm supposed to print the nth term of the fibonacci series
You've already done this part. All you need to do now is to convert the code into a function, which is easy.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int fibonacci(int many)
{
// initialise your variables
// you can write variables of the same type on the same line
// (or multiple lines if you wish)
int remember = 0, num1 = 1, num2 = 1, math = 0;
for(int i = 0; i < many; i++) {
remember = num1;
math = num1 + num2;
num1 = num2;
num2 = math;
}
return remember;
}
and the series up to that number depending on what they user inputs.
Just loop through the Fibonacci numbers starting from the first Fibonacci number and keep printing until the nth Fibonacci number is greater than the inputted number.
For example,
1 2 3
input: 6
output: 8 (6th Fibonacci number)
1 1 2 3 5 (Fibonacci numbers less than 6)