157k views
3 votes
Write a Bash script that takes input from the user to calculate the sum and average of weekly temperatures for a given city as follows.

First, get the city name, prompt the user to enter daily temperatures for the city name, then compute the sum and average weekly temperature based on data entered for each day.
1. Algorithm or strategic approach
• Display city name, total temperature entered, and average temperature
• Use If-Then-Else statements to display the message of the season in the city based on the average temperature entered
• Use CASE Statements to display the same message of the season

User Sue Walsh
by
7.3k points

1 Answer

4 votes

Final answer:

A Bash script can be created to calculate the sum and average of weekly temperatures for a city, using If-Then-Else and CASE statements to deduce and display the season based on the average temperature.

Step-by-step explanation:

To write a Bash script that calculates the sum and average of weekly temperatures for a given city, one must first obtain the name of the city from the user, prompt the user to input daily temperatures, and then perform the calculations based on the provided data. The script will also use If-Then-Else and CASE statements to display a message indicating the likely season in the city, based on the average temperature.

Below is an example Bash script that performs the required tasks:

#!/bin/bash

echo "Please enter the city name:"
read CITY

SUM=0
COUNT=0

echo "Enter the daily temperatures for $CITY (separated by space):"
read -a TEMPERATURES

for TEMP in "${TEMPERATURES[at the rate]}"
do
SUM=$(($SUM + $TEMP))
let COUNT++
done

AVERAGE=$(($SUM / $COUNT))

echo "City: $CITY"
echo "Total Temperature: $SUM"
echo "Average Temperature: $AVERAGE"

if [ $AVERAGE -lt 50 ]; then
SEASON="Winter"
elif [ $AVERAGE -ge 50 -a $AVERAGE -lt 70 ]; then
SEASON="Spring"
elif [ $AVERAGE -ge 70 -a $AVERAGE -lt 80 ]; then
SEASON="Summer"
else
SEASON="Fall"
fi
echo "Season: $SEASON"

case $AVERAGE in
[1-49])
echo "It's Winter in $CITY"
;;
[50-69])
echo "It's Spring in $CITY"
;;
[70-79])
echo "It's Summer in $CITY"
;;
*)
echo "It's Fall in $CITY"
;;
esac

After running the script, the user will be presented with the city name, total temperature, and average temperature. The script then uses the average temperature to determine the season and outputs the corresponding message.

User Moriesta
by
8.3k points