Part (b, & c) i obtained from my book and online, but they have if and while statements. The chapter i got this problem from (ch 3.) deals with (Numeric Types, Expressions, and Output) in which i have yet to cover if and while statements. This is where my problem is, how can i code something, when i haven't learned the constructs of how the answer is given. Thanks & God bless.
A.) // my code
// factorial for value 5 int n = 5; int result = 1; result = n * (n-1) * (n-2) * (n-3) * (n -4); // this seems ok, but if i had to do for a larger number like 18, // it's annoying to think that i would have to type: // result = n *(n-1) *.....(n-17).
//******************************************************************
B.) // code from book from (ch. 7, Functions)
int Factorial(/*in*/ int n)
// This function computes n!
//Precondition: n>= 0 && n! <= INT_MAX
//Postcondition: return value is n!
{
int result; // Holds partial products
result = 1;
while (n > 0)
{
result = result * n;
n--;
}
return result;
}
//*************************************************************
C.) code obtained online from (cplusplus.com)
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}

New Topic/Question
Reply



MultiQuote



|