Function: -
Q) Write a simple script to know
function ?
Ans –
#! /bin/sh
fun()
{
echo “This is my first function”
}
fun
Q) Taking two variables from
keyboard and find summation of it by function.
Ans –
#! /bin/sh
sum()
{
s=`expr $1 + $2`
echo “Result = $s”
}
echo “Enter two values: “
read a b
sum $a $b
Q) Find all arithmetic operation
using function.
Ans –
#! /bin/sh
add()
{
s=`expr $1 + $2`
echo “Sum = $s”
}
diff()
{
d=`expr $1 - $2`
echo “Difference = $d”
}
mul()
{
m=`expr $1 \* $2`
echo “Multiplication = $m”
}
div()
{
di=`expr $1 / $2`
echo “Division = $di”
}
mod()
{
mo=`expr $1 % $2`
echo “Modulus = $mo”
}
echo “Enter two values: “
read a b
add $a $b
diff $a $b
mul $a $b
div $a $b
mod $a $b
Q) Write a script to know return of
value ?
Ans –
#! /bin/sh
sum()
{
s=`expr $1 + $2`
return $s
}
echo “Enter two values: “
read a b
sum $a $b
echo “Result = $?”
Q) Write a script to add first two
numbers and then subtract the third one ?
Ans –
#! /bin/sh
add()
{
s=`expr $1 + $2`
return $s
}
sub()
{
su=`expr $1 - $2`
return $su
}
echo “Enter three numbers: “
read a b c
add $a $b
r=”$?”
sub $r $c
echo “Result = $?”
Q) Write an example to know nested
function ?
Ans –
#! /bin/sh
fun()
{
echo “This is my first function”
func
}
func()
{
echo “This is my second function”
fund
}
fund()
{
echo “This is my last function”
}
fun
Q) Take four values from user input
and add first two ones, then subtract the third one from first addition result
and then multiply fourth one from result of subtraction using nesting function
?
Ans –
#! /bin/sh
add()
{
s=`expr $1 + $2`
diff $s $3 $4
}
diff()
{
di=`expr $1 - $2`
mul $di $3
}
mul()
{
m=`expr $1 \* $2`
echo “Result = $m”
}
echo “Enter four values: “
read a b c d
add $a $b $c $d
No comments:
Post a Comment