Explanation
Here is an explanation of the script:
1. Purpose
This program prompts the user to enter a positive integer and calculates its factorial ($n! = n \times (n-1) \times \dots \times 1$).
2. Key Concepts
- User Input (
read): Captures data entered by the user. - Variables: Stores values in memory (
nandans). - C-Style
forLoop: Repeats a block of code a set number of times. - Arithmetic Expansion (
$(( ... ))): Performs mathematical operations in Bash.
3. Code Walkthrough
#!/bin/bash: The Shebang line telling the system to run this script using the Bash interpreter.read -p "..." n: Displays a prompt message and stores the entered number into the variablen.ans=1: Initializes the accumulator variableansto1(since multiplying by 1 doesn't alter the result).for((i=1;i<=n;i++)): A loop that starts a counter variableiat1and increments it by1until it reachesn.ans=$((ans*i)): Inside the loop, multiplies the current value ofansbyiand updatesans.echo $ans: Prints the final result to the terminal.
4. Output
If you run the program and enter 5:
To Find Factorial of number, Enter a number: 5
120
(Explanation: $1 \times 2 \times 3 \times 4 \times 5 = 120$)