Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

.. Converting an if-else statement into a switch statement #!/bin/bash for x in

ID: 3556310 • Letter: #

Question

..

Converting an if-else statement into a switch statement

#!/bin/bash

for x in $@
do
array[$i]=$x
i=$((i+1))
done


# initial state
state=S0


for((i=0;i<${#array[@]};i++))
do

if [ $state == S0 ]
then
if [ ${array[$i]} == I0 ]
then
state=S1
output[$i]=O1
elif [ ${array[$i]} == I1 ]
then
state=S0
output[$i]=O0
fi

elif [ $state == S1 ]
then
if [ ${array[$i]} == I0 ]
then
state=S1
output[$i]=O1
elif [ ${array[$i]} == I1 ]
then
state=S0
output[$i]=O0
fi
fi


done
echo "final state="$state
echo "output="${output[@]}

Explanation / Answer

#!/bin/bash

for x in $@
do
array[$i]=$x
i=$((i+1))
done


# initial state
state=S0


for((i=0;i<${#array[@]};i++))
do

    case $state in
        "S0")
       case ${array[$i]} in
          "I0")
                state=S1
                output[$i]=O1
       ;;
          "I1")
                state=S0
                output[$i]=O0
               ;;
        esac
        ;;
        "S1")
            case ${array[$i]} in
          "I0")
                state=S1
                output[$i]=O1
       ;;
            "I1")
                state=S0
                output[$i]=O0
       ;;
        esac
        ;;        
          
    esac
  
done
echo "final state="$state
echo "output="${output[@]}