I am trying to write a program that uses a for loop to output the Fibonacci series to the number inputted. I have put the program I have so far, but am having trouble with getting the sum of all the terms
Here are some examples of what the output should look like:
Enter the number of terms in the Fibonacci series>2
F[2] = 0 + 1 = 1
Enter the number of terms in the Fibonacci series>4
F[4] = 0 + 1 + 1 + 2 = 4
Enter the number of terms in the Fibonacci series>8
F[8] = 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 = 33
I would rather not use the fib function...is there a way to solve my problem within the loop I already have or by using another loop in the if statement at the very end of my program?
Code:
#include <iostream>
using namespace std;
int main()
{
cout<<"Enter the number of terms in the Fibonacci series>";
int numOfTerms;
cin>>numOfTerms;
int fib1 = 0;
int fib2 = 1;
int fib = 0;
if (numOfTerms >= 1)
cout<<"F["<<numOfTerms<<"] = "<<fib1;
if (numOfTerms >= 2)
{
cout<<" + "<<fib2;
for (int x = 2; x < numOfTerms; x++)
{
fib = fib + fib2;
cout<<" + "<<fib;
fib1 = fib2;
fib2 = fib;
}
}
int sum;
if (numOfTerms >= 1)
{
sum = numOfTerms - 1 + numOfTerms - 2;
cout<<" = "<<sum;
}
else
cout<<endl;
return 0;
}