for loop

ok so my code is something like this

#include<stdio.h>
int main()
{
int factorial =1, num;
printf ("Enter a value");
scanf ("%d", &num);
if ( num == 0)
factorial = 1;
if (num < 0)
printf ("INVALID!");
if (num > 0)

for (factorial =1; num--;)
{
factorial = factorial * num;
}

printf (" The factorial is %d", factorial );

return 0;

}

When I execute it, any number I enter always end up with an answer 0.





for (factorial =1; num--;) // <= let me clarify factorial is your starting range and you decremented num ? whats your condition for the for loop to run?

and i think you need a code block in your if(num>0) function if you want your for loop to be local to your if(num>0)?
Last edited on
On the final iteration of your loop, num has the value 0, so when factorial = factorial * num; is executed, it is actually executing factorial = factorial * 0;.
so how do I put that right?
I don't know if your logic is right but your for loop would look like this:
1
2
for (factorial = 1; num > 1; num--)
    factorial = factorial * num;
You can debug your own program by placing printf statements (or std::cout) to show the value of relevant variables. This is a problem you could have resolved yourself with a skill that you'll need as long as you are programming.
Topic archived. No new replies allowed.