My professor gave this function to us:
Given a function factorial as follows:
1 2 3 4 5 6 7
int power(int exponent)
{
int i, result=1;
for(i=1;i<=exponent; i++)
result = result * i;
return result;
}
He wants us to write a main routine to test factorial (3) and factorial (10)
We are not using recursive. I know we can do factorial with recursive but that's our next assignment. I'm just wondering how am I supposed to code this. I coded it a few times but each time I got an errors.
This is what I came up with but its pretty messy:
that there is a power function, not a factorial function
Not sure I follow... It looks like a misnamed factorial function to me. A power function would need parameters for the base and the exponent.
@OP You can't declare functions within functions. It looks like your professor has already provided you with a factorial function (which (s)he erroneously calls 'power') and you just need to write int main() that contains the code in Duoas's post.
1 2 3 4 5 6 7 8 9
//#includes up here...
//copy-paste your professor's code here
int main()
{
//Duoas's code here
return 0;
}
EDIT: It also looks like your professor's code doesn't use some unnecessary braces, and this may be a source of confusion for you (judging by your attempt to replicate it). This code is practically identical to your professor's, but maybe it is easier to read:
1 2 3 4 5 6 7 8 9
int factorial(int input)
{
int i, result=1;
for(i=1;i<=input; i++)
{
result = result * i;
}
return result;
}
The biggest takeaway is to notice the placement of the return statement. It doesn't go inside the loop!
Thanks for the help guys! The build succeeded but it keeps closing out. I even put a system pause at the end of the main function. Even thought I'm pretty sure I did not have to. So I cant even check to make sure the program is right. Any clues.