-
While loop question!
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
float fact;
/* what number do we want to calculate the factorial of? */
num = 10;
/* Initialise the factorial */
fact = 1.0;
/* Count from 2 to num, multiply fact by counter each time */
i = 2;
while ( i <= num) {
fact = fact * i;
i = i + 1;
}
/* Print the result */
printf (“The factorial of %d is %f\n”, num, fact);
}
The point of that was to calculate the factorial of 10, using a while loop, which worked fine, but I have this question that says Alter the program so that the counter counts from num down to 1, rather than the other way .
I tried altering the code in the following way but it didn’t work:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
float fact;
/* what number do we want to calculate the factorial of? */
num = 10;
/* Initialise the factorial */
fact = 1.0;
/* Count from 10 to num, multiply fact by counter each time */
i = 10;
while ( 0< i <= num) {
fact = fact * i;
i = i - 1;
}
/* Print the result */
printf (“The factorial of %d is %f\n”, num, fact);
}
Which should give me the same answer as the first code written but it doesn’t. Where have I gone wrong?
Thanks!
-
Code:
while ( 0< I <= num)
This doesn't do what you think it does.
-
i is not declared.
Is this the actual code that you compiled? If it is, what compiler are you using, and what is your warning level set to?
-
You can use this for while
Code:
While(0<l && l<=num)
but in your program l is undeclared . . . Check it out
-
What do you mean i is not declared...?
I used emacs as the editor.. and i've edited the code slightly maybe it was that..what you mean?
-
It means you're not telling the compiler what i is. The same goes for num. The compiler can't just guess "oh, i is an int, num is also an int" you have to declare to the compiler that they are.
In code :
-
> While(0<l && l<=num)
Capital i, or any case of L are terrible names for variables. It's also while() not While() ;)
0 < I <= num, is the same as, i E(0,num], in other words
Code:
if(i > 0 && i <= num)
/* in range */