Writing MATLAB program
Writing MATLAB
function

Program Statements:
- Firstly, a menu is displayed which gives an option for user to select whether factorial is to be calculated by function or without function.
- Prompt the user to enter a choice and number n.
- Input choice and n whose factorial is to calculated.
- If choice is 2, calculate factorial without function
- Use for loop that iterates from value 1 to n and calculate factorial.
- Else if choice is 1 then calculate the factorial with function
- Call a function fact with the argument k.
- Then the print the factorial of the number.
- Function definition of fact contain below statements:
- The base condition returns 1 when number becomes 1
- Second condition will goes on until the factorial of the number is calculated using recursive call.
MATLAB code to find factorial of a number using function and without using function:
disp("1 for factorial using function");
disp("2 for factorial without function");
// These two will show the menu
ch=input("enter a choice");
n = input("enter a number for fact");
// This will take the number from user
if (ch==2)
f = 1;
for i = 1:n // loop from 1 to n
f = f*i; // multiplying until i=n
end // end for loop
else if(ch==1)
k=n
kFactorial = fact(k); // function call
fprintf('%d! = %d\n', k, kFactorial);
// Prints factorial
else
disp("select correct option");
end
end
function x = fact(n) // function definition
if n<=1 // goes when n<=1
x = 1;
else
x = n .* fact(n-1) ; // recursive function call
end
end
Step by step
Solved in 3 steps with 2 images









