431,661 Members | 779 Online
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   #include  #include  // 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; }     Oct 8 '10 #1

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.

4 Replies

 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

 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