Why am I getting an infinite loop when I add a while statement?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • houstonkv
    New Member
    • Sep 2010
    • 4

    Why am I getting an infinite loop when I add a while statement?

    Hi!
    im working on this modified fibianoci problem for class and although i cant ever spell fibinoci right
    I did manage to work out the function as my teacher has requested.

    unforutnetly when i put the finishing touches on the code and added a while loop so the user could exit by typing -1 i am presented with an infinite loop of seemingly random numbers.

    I assume Im missing a bracket somewhere but i just cant find it.

    thoughts?
    hints?
    suggestions?

    thank you to everyone

    Code:
    #include <stdio.h>
    #include <math.h>
    // This is Lab4Part1
    //  998275842
    // Houston Keil-Vine
    // Creates a sting of numbers
    // using the previous 2 numbers.
    
    int main (void)
    {
    	int f3=1;
    	int f2=0;
    	int f1=1;
    	int f4=1;
    	int n=0;
    	int counter=0;
    	
    	
    	
    	printf("Enter a non-negative integer  or enter -1 to quit:\n");
    	scanf("%d",&n);
    	
    		while(n>0) {
    		
    		
    			for(counter=0; counter<=n; counter++)
    			
    			{
    				printf("%d ",f4);
    				f4=f1+f2;
    				f1=f2;
    				f2=f3;
    				f3=f4;	
    			}
    			printf("\n");
    		}
    	
    return 0;
    }
  • Meetee
    Recognized Expert Contributor
    • Dec 2006
    • 928

    #2
    For eg, you give n = 5. Now when it goes in while loop, every time it gets n = 5 which is > 0. You are not decreasing n's value during each iteration. So it's going into infinite loop.

    Comment

    • houstonkv
      New Member
      • Sep 2010
      • 4

      #3
      I understand!
      how can i get the program to keep repeating (asking for new integers) with out getting the infinite loop?
      (well still having the typ -1 to exit?

      Comment

      • Meetee
        Recognized Expert Contributor
        • Dec 2006
        • 928

        #4
        Remove while loop to get rid of this problem. (for loop is OK)

        And please check your logic again. I see problem in that too.

        Comment

        • houstonkv
          New Member
          • Sep 2010
          • 4

          #5
          thanks so much for responding so quickly
          I think i got it though!

          we get a tester program to run it again and apperantly it all checks out.

          I did finally catch the logic mistake.
          thanks for the heads up
          and for all your help.

          Comment

          Working...