Wednesday 15 October 2014

How to write a shell script to find factorial of number

We are going to find factorial of numbers. Factorials are a very important part of algebra, particularly series mathematics.
Here is a program written in bash shell script to find factorial of all the numbers from 0 to n where n is a number enter by user.


#!/bin/bash
#Author: Subhroneel Ganguly
#Date: 15.10.2014

echo Enter Range:
read RANGE
# UM is asigned to 0. We are starting from 0 and NUM will go until RANGE and factorial will be calculated from 0 to RANGE.
NUM=0
while [ "$NUM" -le "$RANGE" ]
        do
# FACT is initialize to 1, this has to advantages. One is obvious that we can easily multiply incremented numbers to it to calculate factorial. Another is for 0
# and 1 we will by default get factorial calculated, without entering the loop.       
        FACT=1
# Starting I from 2 (Number for which factorial will be calculated, 0 and 1 is excluded as we have already calculated factorial of it as FACT=1       
        I=2
        while [ "$I" -le "$NUM" ]
        do
# Incremented value of I is multiplied to FACT, (logic of factorial) 5 x 4 x 3 x 2 x 1 for NUM=5
                let FACT*=I
                let I+=1
        done
        echo Factorial of $NUM is $FACT
        let NUM+=1
done

Also can subscribe to my channel in youtube : https://www.youtube.com/subhro190776

No comments: