This is my program, and I want it to display the nth fibonacci number if I
enter n.
I want to do this without recursion. What is wrong?
include <stdio.h>
include "genlib.h"
include "simpio.h"
int fib(int n);
main ()
{
int n, f;
printf ("Please enter an integer. \nThis program will find the nth fibonacci
number. \nn = ? ");
n=GetInteger ();
printf ("\n%d\n", fib(n));
system ("PAUSE");
}
int fib(int n)
{
int n_check, f;
if (n==0) {f=0; return 0; }
else {
if (n==1) {f=1; return 1; }
else {while (n_check<n)
f=f+n_check;
n_check=n_check+1;
}
}
return f;
}
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
if (n == 0)
{
f = 0; // why?, f is never used
return 0;
}
else
{
if (n == 1)
{
f = 1; // again f isn't used
return 1;
}
else
{
while (n_check < n) // n_check isn't initialized to anything, results
unpredictable, loops forever or not at all
f = f + n_check; // f was never initialized, unpredictability ^ 2
n_check = n_check + 1; // I think you intended this to be part of the while
loop (?), you need brackets
}
}
return f;
}
I hope this helps
TW
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
This is my program, and I want it to display the nth fibonacci number if I
enter n.
I want to do this without recursion. What is wrong?
include <stdio.h>
include "genlib.h"
include "simpio.h"
int fib(int n);
main ()
{
int n, f;
printf ("Please enter an integer. \nThis program will find the nth fibonacci
number. \nn = ? ");
n=GetInteger ();
printf ("\n%d\n", fib(n));
system ("PAUSE");
}
int fib(int n)
{
int n_check, f;
if (n==0) {f=0; return 0; }
else {
if (n==1) {f=1; return 1; }
else {while (n_check<n)
f=f+n_check;
n_check=n_check+1;
}
}
return f;
}
int fib(int n)
{
int n_check, f;
if (n == 0)
{
f = 0; // why?, f is never used
return 0;
}
else
{
if (n == 1)
{
f = 1; // again f isn't used
return 1;
}
else
{
while (n_check < n) // n_check isn't initialized to anything, results
unpredictable, loops forever or not at all
f = f + n_check; // f was never initialized, unpredictability ^ 2
n_check = n_check + 1; // I think you intended this to be part of the while
loop (?), you need brackets
}
}
return f;
}
I hope this helps
TW
Thanks for the help, but that gives me a linker error. :(