Thread: c++ Program to find the sum of the Fibonacci Series

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    1

    c++ Program to find the sum of the Fibonacci Series

    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;
    }
    Last edited by newbie09; 02-28-2011 at 12:27 AM.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    You would have to sum fib(8) + fib(7) + fib(6) + fib(5) + fib(4) + fib(3) + fib(2) + fib(1) for example, if you made no changes to a Fibonacci function.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To Find Largest Consecutive Sum Of Numbers In 1D Array
    By chottachatri in forum C Programming
    Replies: 22
    Last Post: 07-10-2011, 01:43 PM
  2. sum of the series - loop?
    By jacek in forum C Programming
    Replies: 20
    Last Post: 10-25-2009, 11:46 PM
  3. Minor Problem
    By stewie1986 in forum C Programming
    Replies: 6
    Last Post: 11-30-2007, 08:40 AM
  4. Program to determine sum
    By jadedreality in forum C++ Programming
    Replies: 17
    Last Post: 10-09-2007, 11:48 PM