Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

03 December 2012

Shell Script to find factorial of a number using Recursion

2 comments

Q. How do I find factorial of a number using recursion function in Bash


Ans:

#!/bin/bash
#Recursive factorial function
factorial()
{
local=$1
if((local<=2)); then
echo $local
else
f=$((local -1))
#Recursive call
f=$(factorial $f)
f=$((f*local))
echo $f
fi
}
#main script
read -p "Enter the number:" n
if((n==0)); then
echo 1
else
#calling factorial function
factorial $n
fi
Read More...

30 November 2012

Shell Script to find "a" to the power "b" using function

1 comment

Q. How do I write Shell Script function to find "a" to the power "b"


Ans.

#!/bin/bash
#function to find "a" to the power "b"
power()
{
num=$1
pow=$2
counter=1
result=1
if((pow==0)); then
result=1
fi
if ((num==0)); then
result=0
fi
if((num>=1&&pow>=1)); then
while((counter<=pow))
do
result=$((result*num))
counter=$((counter + 1))
done
fi
#Printing the result
echo "$1 to the power $2 is $result"
}

#main script
read -p "Enter number:" num
read -p "Enter power:" pow

#calling above function
power $num $pow
Read More...

20 January 2012

Shell Script to add two numbers by the use of Function

13 comments

Q. How do I write Bash Script to add two numbers using function


Ans:

#!/bin/bash
#function to add two numbers
add()
{
x=$1
y=$2
echo -e "Number entered by u are: $x and $y"
echo "sum of $1 and $2 is `expr $x + $y` "
}
# main script
echo "enter first number"
read first
echo "enter second number"
read sec
#calling function
add $first $sec
echo "end of the script"
Read More...