Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following basic definition of a factorial function for any positive

ID: 3700310 • Letter: C

Question

Consider the following basic definition of a factorial function for any positive integer: Factorial (n) = n* (n-1) *...... * 1. For example, Factorial(4) = 4 * 3 * 2 * 1 = 24. Factorial (0) = Factorial (1) =1. Write informal pseudo code or alogorithm to compute factorial of any positive integer. 1) using iterative (repeat) structure 2) using recurusive structure Which is an example of top-down or bottom-up structure? How do you assess correctness of your pseudo code (hint: what is the loop invariant, condition?)

Explanation / Answer

Iterative Method:

int res=1;

for(int i=1; i<=N; i++)

{

res*=i;

}

return res;

Loop invariant condition is i=1 and increases till n;

Recursive Method:

int factorial(int n)

{

if(n==1 || n==0)

return 1;

return n*factorial(n-1);

}

The loop invariant condition is that 0!=1 and 1!=1. So when o or 1 is encountered as n, we simply return 1;

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote