GTU OS Program - 4
4. Write a shell script to find factorial of given number n.
As we have done this program many times in our programming career the logic will be same but there will be some changes in syntax.
Start by creating a new file called factorial.sh using vim
tkanu025@hp:~/lab_solutions$ vim factorial.sh
Complete code of the program
- fact=1
- read -p "Enter a number to find its factorial : " n
- #if entered value is less than 0
- if [ $n -le 0 ]
- then
- echo "invalid number"
- exit
- fi
- #logic for finding factorial
- a=$n
- while [ $a -ge 1 ]
- do
- fact=`expr $fact \* $a`
- a=`expr $a - 1`
- done
- echo "Factorial of $n is $fact"
Interpreting the factorial.sh file and executing it in terminal
- tkanu025@hp:~/lab_solutions$ chmod +x factorial.sh
- tkanu025@hp:~/lab_solutions$ ./factorial.sh
And here is the output

Comments