Create a function “my_factorial” that takes in an input argument ‘n’ and returns
ID: 3801799 • Letter: C
Question
Create a function “my_factorial” that takes in an input argument ‘n’ and returns the factorial of a given number. Factorial of a given integer is the product of the integer and all the positive integers it. For instance, if your input is 5, your function should return 120 which is equal to 5x4x3x2x1. You are to implement this function without using any built-in MATLAB function and using only for / while loops. Write a script file “run_my_factorial” to call the function. Script file should allow the user to enter the value (input command) that he wants to compute factorial for and display the factorial value. However, if the value entered is not in the desired form [Not a positive integer], your code should not terminate (i.e. should not break), instead you should allow the user to re-enter until he enters it as desired. You may assume that user will check only for negative values/ decimal values. You may use round() command if needed.
((use matlab))
Explanation / Answer
#save as run_my_factorial.m
#set repeat to true
repeat=true ;
#repeat the while loop until user enters a valid integer
while repeat
#prompt user to enter a positive value
value=input('Enter a positive integer : ');
#check if value is negative
if value<0
fprintf('Enter positive integer ')
repeat=true;
#check if it is a decimal value
elseif value !=round(value)
value=round(value)
repeat=false ;
else
repeat=false;
end
end
%finding the factorial of a number
f = 1;
for i = 1:value
f = f*i;
end
fprintf('Factorial of %d is %d ',value,f);
----------------------------------------------------------------
Sample output:
Enter a positive integer : 5.5
value = 6
Factorial of 6 is 720 >> run_my_factorial
Enter a positive integer : 6.8
value = 7
Factorial of 7 is 5040 >> run_my_factorial
Enter a positive integer : 4.6
value = 5
Factorial of 5 is 120 >> run_my_factorial
Enter a positive integer : -5
Enter positive integer
Enter a positive integer : 5
Factorial of 5 is 120 >>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.