Search code examples
bashmultiplication

Bash Scripting Multiplication table


Hello I am wondering if anyone can help me : I try to make a multiplication table for my daughter, I don't know how to make it. This is how I want to look : 1 x 1 = ? answer if the answer is true then go to the next one 1 x 2 = ? but if the answer is false then ask again 1 x 1 = ? until the answer is Correct.

#!/bin/bash

# Multiplication table 

echo " --== Multiplication Table ==-- "
sleep 2
echo " Lesson 1"
sleep 1
echo ""


echo -n "1 x 1 = ? " ; read opt
if [ "$opt" = 1 ] 
then
echo "Correct!"
else 
echo "Wrong!"
fi

sleep 1 
echo ""
echo -n "1 x 2 = ? " ; read opt
if [ "$opt" = 2 ] 
then
echo "Correct!"
else 
echo "Wrong!"
fi

After the exercise is done until 10. Then show a result of how many correct answers has and how many Wrong. Example: Lesson 1 is finish you have 9 correct answers and 1 wrong answer !


Solution

  • You can use this script:

    #!/bin/bash
    
    # Multiplication table
    
    echo " --== Multiplication Table ==-- "
    sleep 2
    echo " Lesson $1"
    sleep 1
    echo ""
    
    wrong=0
    correct=0
    for i in {1..10}
    do
        while true
        do
            echo -n "$1 x $i = ? " ; read opt
            if [ $opt = $(( $1 * $i )) ]
            then
                (( correct++ ))
                echo "Correct!"
                break
            else
                (( wrong++ ))
                echo "Wrong!"
            fi
        done
    done
    
    echo "Lesson $1 is finish you have $correct correct answers and $wrong wrong answer!"
    

    You can run it with different params for any base. Such as ./script 5 for multiplication with 5.