Answer to Question #245653 in C for joe

Question #245653

Write a bash script that takes two arguments as command-line arguments for the above arithmetic operations (add, sub, mul, div and exp). The first argument should be the name of the operations, ie. -- ‘add’, ‘sub’, ‘div’, and ‘exp’. The subsequent arguments should be two (or more) operands. Thus, depending upon the operations requested, you may call the appropriate function (bash subroutine), which should perform the corresponding arithmetic operation, using the supplied arguments.



1
Expert's answer
2021-10-02T10:56:16-0400
#!/bin/bash

add () {
    echo $(( $1 + $2 ))
}

sub () {
    echo $(( $1 - $2 ))
}

mul () {
    echo $(( $1 * $2 ))
}

div () {
    echo  $(( $1 / $2 ))
}

exp () {
    if [ $2 -eq 0 ]
    then
        echo 1
    else
        p=$(( $2 - 1 ))
        x=$( exp $1 $p )
        (( x *= $1 ))
        echo $x
    fi
}

if [ $1 == "add" ]
then
    x=$( add $2 $3 )
elif [ $1 == "sub" ]
then
    x=$( sub $2 $3 )
elif [ $1 == "mul" ]
then
    x=$( mul $2 $3 )
elif [ $1 == "div" ]
then
    x=$( div $2 $3 )
elif [ $1 == "exp" ]
then
    x=$( exp $2 $3 )
fi

echo $x

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS