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

CS365WI A Small Test with BASH The main task of the project is to write a bash s

ID: 3743737 • Letter: C

Question

CS365WI A Small Test with BASH The main task of the project is to write a bash script to have a guessing game. The bash script when executed, will give the output on the terminal. It will first put out a welcoming message and request the user to guess a number (a positive integer) which the script has generated randomly. If the guessed number is bigger than the number that the script has generated, it will give out a message that "Your guess is too high so try again. If the guessed number is lower than the number that the script has generated, it will give out a message that "Your guess is too low so try again." When the user types his guess, if the number is correctly guessed, then it will congratulate the user, tel the number of attempts taken to guess correctly and halt. You must comment your bash script properly for every line of code. Name the file as CS465WI

Explanation / Answer

Bash:

# Actually we are taking input from user each time and comparing it with random generated number and displaying the message if they are not
# equal and running the loop.

#!/bin/bash
echo "Welcome User.Please guess a random positive number within the range 0 to 100."       # Welcoming Message with request.
read usernumber                                           # User input.
randomnumber=`expr $RANDOM % 101`       # generating random number and modulo is taken to bring the number within the range.
count=1                       # Number of attempts taken by user initialized with 1.
while [ $randomnumber -ne $usernumber ]    # loop until the user guess is not equal to random generated number.
do
    if [ $randomnumber -lt $usernumber ]; then
        echo "Your guess is too high so try again."
    elif [ $randomnumber -gt $usernumber ]; then
        echo "Your guess is too low so try again."
    fi
    read usernumber
    count=`expr $count + 1`
done
echo "Congratulations User!!!.You took $count attempts to guess correctly."   # Congratulation greetings.