In: Computer Science
The factorial of a natural number n is denoted by n! and is defined as follows:
the factorial of 0 is 1, the factorial of 1 is 1, and the factorial of any other positive integer is the product of all the integers from 2 to that integer.
Write a VBA function called MyFactorial with one input of data type Integer which computes and returns the value of the factorial of the input if it is greater than or equal to 0 and returns -1 if the input is a negative integer.
Test the function with the following values: 5! = 120, 6! = 720, 7! = 5040, 8! = 40320, 9! = 362880.
VBA code:
Function MyFactorial(Value As Long) As Long
If Value = 0 Or Value = 1 Then
MyFactorial = 1
ElseIf Value < 0 Then
MyFactorial = -1
Else
MyFactorial = MyFactorial(Value - 1) * Value
End If
End Function
Screenshot of code:
Output:
Steps to run the code:
1) Write the code in the VBA editor of Excel
2) Go to sheet
3) Make a column for 'Number' and 'Factorial'
4) Write the numbers you need the factorial for in the 'Number' column
5) Under the factorial column write the formula "=MyFactorial("Cell number")" and press enter.