By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,661 Members | 779 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,661 IT Pros & Developers. It's quick & easy.

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

P: 4
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

Expand|Select|Wrap|Line Numbers
  1.  
  2. #include <stdio.h>
  3. #include <math.h>
  4. // This is Lab4Part1
  5. //  998275842
  6. // Houston Keil-Vine
  7. // Creates a sting of numbers
  8. // using the previous 2 numbers.
  9.  
  10. int main (void)
  11. {
  12.     int f3=1;
  13.     int f2=0;
  14.     int f1=1;
  15.     int f4=1;
  16.     int n=0;
  17.     int counter=0;
  18.  
  19.  
  20.  
  21.     printf("Enter a non-negative integer  or enter -1 to quit:\n");
  22.     scanf("%d",&n);
  23.  
  24.         while(n>0) {
  25.  
  26.  
  27.             for(counter=0; counter<=n; counter++)
  28.  
  29.             {
  30.                 printf("%d ",f4);
  31.                 f4=f1+f2;
  32.                 f1=f2;
  33.                 f2=f3;
  34.                 f3=f4;    
  35.             }
  36.             printf("\n");
  37.         }
  38.  
  39. return 0;
  40. }
  41.  
  42.  
Oct 8 '10 #1

✓ answered by Meetee

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.

Share this Question
Share on Google+
4 Replies


Meetee
Expert Mod 100+
P: 931
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.
Oct 8 '10 #2

P: 4
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?
Oct 8 '10 #3

Meetee
Expert Mod 100+
P: 931
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.
Oct 8 '10 #4

P: 4
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.
Oct 8 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.