# Need help with break in do while loop

• 03-19-2008
JoelearningC
Need help with break in do while loop
Hi All,
I'm wondering if anyone can tell me where to put the "break" statement in the code below. I'm trying to make it so the program will keep asking a user to input a positive integer and then output it's factorial. However, the first iteration gets caught up in a continual loop. For example, instead of outputing the factorial of the integer 4, for example, just once and then prompting the user to input another integer I just get the output such as:

4! = 24
4! = 24
4! = 24
4! = 24
4! = 24
...etc. continuing on forever.

Can anyone help? Thank you in advance! Joe

Code:

```#include <stdio.h>   int main() { // Program calculates factorial of user inputted integer     long int x,y,result;     x=-1; // Controls for negative integer inputted; can only accept positive integer   printf("Please enter a positive integer:");   scanf("%d",&x);   do {   // Calculates the factorial   result = 1;   for (y=x;y>=1;y--)         result = result*y;   printf("%d! = %d\n",x,result);   } while (x!=0);           printf("Negative integer inputted, Please Try Again!!!\n");   return 0; }```
• 03-19-2008
zacs7
Code:

```  do {   // Calculates the factorial   result = 1;   for (y=x;y>=1;y--)         result = result*y;   printf("&#37;d! = %d\n",x,result);   } while (x!=0);```
x is never going to be 0 unless it's initially entered as 0.

Consider this,
* Ask for a number, n
* multiply n - 1, n - 2, n - 3, ... n - n and put in 'result'
* print result

Start you loop at 1 working your way upto n (the integer the user entered) -- remember don't include 0 in the factorial calculation, ie
Code:

```for(counter = 1; counter < number they entered; counter++) {     /* do calculation with 'counter' */ }```
• 03-19-2008
JoelearningC
can you help more?
HI Zacs7,
Thanks for the assistance. I'm too much of a beginner to even understand what you're talking about much less where I'd put the counter statement. Can you help more in terms of which mistakes I should correct and where to put a break statement? Thanks again.
Joe
• 03-20-2008
iMalc
You've written code without knowing what it does.
I think the best thing you can do is to use your debugger to step through the code one line at a time. That will show you exactly what it is doing at each step and you will learn a lot. It should also show you what you are doing wrong.