Menu

Fibonacci Program Help?

2011-03-04
2012-09-26
  • Ahaan Rungta

    Ahaan Rungta - 2011-03-04

    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;
    }

     
  • tronwizard

    tronwizard - 2011-03-10

    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

     
  • Ahaan Rungta

    Ahaan Rungta - 2011-03-13

    Thanks for the help, but that gives me a linker error. :(

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.