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

terative factorial: Finish the provided factorial function, so that it returns t

ID: 3932803 • Letter: T

Question

terative factorial: Finish the provided factorial function, so that it returns the value n!. Your code should use a forloop to compute the product 1 * 2 * 3 * ... * n. If you write the code carefully, you won't need a special case for when n equals 0.

Once implemented, uncomment the Program.assertEqual() statements at the bottom to verify that the test assertions pass.

var factorial = function(n) {
var result = 1;
for(var i = ......; i <= ..... ; ......) {
.......;
}

return result;
};

println("The value of 5! should be " + 5*4*3*2*1);
println("The value of 5! is " + factorial(5));
println("The value of 0! should be 1");
println("The value of 0! is " + factorial(0));

//Program.assertEqual(factorial(5), 120);
//Program.assertEqual(factorial(0), 1);

Explanation / Answer

public static int factorial(int n) {

       int result = 1;
       for (int i = 1; i <= n; i++) {
           result *= i;
       }
       return result;
   }

   @Test
   public void testFactorials() {
       assertEquals(factorial(5), 120);
       assertEquals(factorial(0), 1);
   }

   public static void main(String[] args) {

       System.out.println("The value of 5! should be " + 5 * 4 * 3 * 2 * 1);
       System.out.println("The value of 5! is " + factorial(5));
       System.out.println("The value of 0! should be 1");
       System.out.println("The value of 0! is " + factorial(0));

   }