fibonacci sequence help

Hey guys, I'm writing some code to output a fib sequence up to a certain term. My problem is that it adds one more to the sequence.. ex if i enter 9 terms it returns up to the 10th.

enter 9 i get 55 with is the 10th. any pointers on how to fix this would be great!

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
  #include <iostream>
#include <iomanip>

using namespace std;

int fib(int n)
{
    int first = 0, second = 1, next;
    for(int i = 0; i < n; i++) 
    {
            next = first + second;
            first = second;
            second = next;
            cout << next << endl;
            
    }
    return 0;
}
int main() 
{
    //Xn = Xn-1 + Xn-2
    int number;
    cout << "Enter the number of terms you want in the fib sequence: ";
    cin >> number;
    fib(number);
    system("pause");
    return 0;
}
The first term of the sequence is fixed, so print that and then compute the terms thereafter. This code works for the first two terms being 1 and 1. Sometimes they are defined as 0 and 1:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void fib(int n)
{
    int first = 0, second = 1, next;
    if (n>0) {
	cout << 1 << endl; // print the first term
	for(int i = 2; i <= n; i++) // print the 2nd through nth terms
	    {
		next = first + second;
		first = second;
		second = next;
		cout << next << endl;
            
	    }
    }
}

Note that I changed the function type from int to void since you don't return anything useful.
Make loop to loop one less time
@dhayden Thanks for the reply, i understand it now.
Topic archived. No new replies allowed.