Fibonacci Sequence

Hey guys so I am trying to modify this without using function pointers. And so that I do not have to use a file to show the results. I'm not sure where to start modifications.

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
35
36
37
38
39
40
  #include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;


int fib(int n)
{
    if (n == 0)
        return 0;
    if (n == 1)
        return 1;
    
    
    return fib(n - 1) + fib(n - 2);
        
}

int main()
{
	FILE *fptr = fopen("Fibonacci.txt", "w");
    if(fptr == NULL)
    	printf("This is an error!");
    else
    {
    fprintf(fptr, "%d\n", fib(4)); // Fibonacci sequence at 2
    fprintf(fptr, "%d\n", fib(8)); // Fibonacci sequence at 8
    fprintf(fptr, "%d\n", fib(12)); // Fibonacci sequence at 12
	}


fclose(fptr);

system("pause");
return 0;

}
You're not currently using function pointers as far as I can tell..

If you don't want to use files, then get rid the fopen/fclose, and just use printf instead of fprintf.
http://www.cplusplus.com/reference/cstdio/printf/

Or, better yet, use cout. This is C++, and you're already including <iostream>.
cout << fib(4) << '\n';
Last edited on
change the file pointer to ofstream. I know you know that ... your other program has one in it.
get rid of the c headers.
fib is like factorial... you can't get very far with it in 64 bits, so a lookup table is really the way to go if you just want the answers. Theres a way to get it from an equation as well, but you have roundoff to deal with. I think you can cram right at 100 values in a 64 bit int so its a relatively tiny table. Whole thing becomes like 4 lines of code.
Last edited on
Thank you. I changed it to something much simpler.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

int fib(int n);

int main()
{
    // Testing the first 4 values of the Fibonacci sequence
    for (int i = 0; i < 4; i++){
        cout << "fib(" << i << ") = " << fib(i) << endl;
    }
}

int fib(int n)
{
    if (n == 0)
        return 0;
    if (n == 1)
        return 1;

    return fib(n-1) + fib(n-2);
}
Topic archived. No new replies allowed.