Thread: big trouble in little program

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    9

    Angry big trouble in little program

    I keep getting an infinate loop for some reason and I cannot figure out why. This is a Fibonacci program that is a large pain in my ass. I need to add a print function aswell but I am not sure how to go about it. Any ideas. Here is my program.


    scanf("%d",&b);
    c=cal_fibonacci(b);
    }

    int cal_fibonacci (int d)
    {
    int f1;
    int f2;
    int fnew, temp;
    int x;

    for(x=1;x<d;++x)
    {
    while (x<3)
    {
    printf("%d" "1",x);
    printf("F1=1");
    printf("F2=1");
    }
    fnew=f1+f2;
    printf("%d" "%d",x,fnew);
    f1=temp;
    f2=f1;
    f2=fnew;
    }

    }

  2. #2
    Unregistered
    Guest
    You forgot to increment the inner loop, therefore the stopping condition is never met and you have an infinite loop.
    Code:
        scanf("%d",&b); 
        c=cal_fibonacci(b); 
    } 
    
    int cal_fibonacci (int d) 
    { 
        int f1; 
        int f2; 
        int fnew, temp; 
        int x; 
    
        for(x=1;x<d;x++) 
        { 
            while (x<3) 
            { 
                printf("%d" "1",x); 
                printf("F1=1"); 
                printf("F2=1");
                x += 1;  /* Without an increment, you have an infinite loop */ 
            } 
        fnew=f1+f2; 
        printf("%d" "%d",x,fnew); 
        f1=temp; 
        f2=f1; 
        f2=fnew; 
        } 
    }
    Your program will also only work once since you're using x as a counter for both loops, it goes through the inner loop once and won't do it again because x will be 3. You can solve a Fibonacci problem with only one loop. Simpler is better.
    Code:
    long fibonacci ( int n ) {
        long result;
        long previous;
        long next_old;
    
        result = previous = 1;
      
        while ( n > 2 ) {
            n -= 1;
            next_old = previous;
            previous = result;
            result = previous + next_old;
        }
        return result;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program Plan
    By Programmer_P in forum C++ Programming
    Replies: 0
    Last Post: 05-11-2009, 01:42 AM
  2. Trouble running a program Visual Studio
    By Swerve in forum C++ Programming
    Replies: 8
    Last Post: 03-03-2008, 11:15 AM
  3. Using variables in system()
    By Afro in forum C Programming
    Replies: 8
    Last Post: 07-03-2007, 12:27 PM
  4. My First BIG program done!!! Check it out!!
    By biosninja in forum C++ Programming
    Replies: 8
    Last Post: 09-04-2002, 03:33 PM