Fibonacci sequence

Im trying to make this program write out only the last number in the fibonacci sequence right now i always get the whole sequence any ideas??

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
 #include <iostream>
using namespace std;

int main()
{
   int n;
   cin >> n;
   int first = 0;
   int second = 1;
   int third;
   for (int i = 0; i < n; i++)
   {
       if(i==0)
    {
            cout << second << " ";
    }
    else
    {
        third = first + second;
        first = second;
        second = third;
        cout << third << " ";
    }
    }
    }
Last edited on
move the print statement out of the loop and change the if print to third = second. Third is your result either way, then.

there are a couple of ways to directly compute the nth term, if you want to play around with that.


Last edited on
Thx it worked!
Topic archived. No new replies allowed.