I can't figure out the end of this Fibonacci series program

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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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;
}


Last edited on
Topic archived. No new replies allowed.