Write a shell script to find factorial of an user-defined natural number.
Question
Write a shell script to find factorial of an user-defined natural number.
🧐 Not the exact question you are looking for?Go ask a question
Solution 1
Sure, here is a simple shell script to calculate the factorial of a user-defined natural number:
#!/bin/bash
# Function to find factorial
factorial()
{
if [ $1 -eq 1 ]
then
echo 1
else
local temp=$1
local result=$(factorial $((temp-1)))
echo $((temp * result))
fi
}
# Read the number from the user
echo "Enter a number:"
read number
# Check if the number is a positive integer
if [[ $number =~ ^[0-9]+$ ]]
then
# Call the factorial function
result=$(factorial $number)
echo "The factorial of $number is: $result"
else
echo "Please enter a positive integer."
fi
Here's how it works:
- The script starts with
#!/bin/bashwhich tells the system that this is a Bash script. - We define a function
factorial()that calculates the factorial of a number. It uses recursion to calculate the factorial. - We read the number from the user with the
readcommand. - We check if the number is a positive integer using a regular expression.
- If the number is a positive integer, we call the
factorial()function and print the result. - If the number is not a positive integer, we print an error message.
Solution 2
Sure, here is a simple shell script to calculate the factorial of a user-defined natural number:
#!/bin/bash
# Function to find factorial
factorial()
{
if [ $1 -eq 0 ]
then
echo 1
else
local temp=$1
local result=$((temp * $(factorial $((temp-1)))))
echo $result
fi
}
# Ask user for the input
echo "Enter a number:"
read number
# Check if number is a positive integer
if ! [[ "$number" =~ ^[0-9]+$ ]]
then
echo "Error: Input must be a positive integer."
exit 1
fi
# Call factorial function
result=$(factorial $number)
# Print the result
echo "The factorial of $number is: $result"
Here's how this script works:
- The script starts with
#!/bin/bashwhich tells the system that this is a Bash script. - We define a function
factorial()that calculates the factorial of a number. This function calls itself recursively. - We ask the user to enter a number and read this number into the
numbervariable. - We check if the number is a positive integer. If not, we print an error message and exit the script.
- We call the
factorial()function with the user's number and store the result in theresultvariable. - Finally, we print the result.
Similar Questions
Write a program to calculate the factorial of N.
Write a python function to find the factorial of given number
write a recursive function to find factorial of a number.
Python Program to Find the Factorial of a Number Without Recursion
00:47Write a program to find a factorial of a number
1/3
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.