Lab Task 3
Question1
Write a script that presents a menu with options like "Add", "Subtract", "Multiply",
and "Divide". Based on the user's choice, perform the corresponding operation. Take the
operands from the user as well.
Code
~$ #!/bin/bash
~$
~$ # Function to display the menu
~$ display_menu() {
> echo "Select an operation:"
> echo "1. Add"
> echo "2. Subtract"
> echo "3. Multiply"
> echo "4. Divide"
> echo "5. Exit"
>}
~$
~$ # Main loop
~$ while true; do
> display_menu
> read -p "Enter your choice (1-5): " choice
>
> if [[ $choice -eq 5 ]]; then
> echo "Exiting..."
> break
> fi
>
> read -p "Enter first operand: " operand1
> read -p "Enter second operand: " operand2
>
> case $choice in
> 1)
> result=$((operand1 + operand2))
> echo "Result: $operand1 + $operand2 = $result"
> ;;
> 2)
> result=$((operand1 - operand2))
> echo "Result: $operand1 - $operand2 = $result"
> ;;
> 3)
> result=$((operand1 * operand2))
> echo "Result: $operand1 * $operand2 = $result"
> ;;
> 4)
> if [[ $operand2 -eq 0 ]]; then
> echo "Error: Division by zero is not allowed."
> else
> result=$((operand1 / operand2))
> echo "Result: $operand1 / $operand2 = $result"
> fi
> ;;
> *)
> echo "Invalid choice. Please select a valid option."
> ;;
> esac
> done
Output
Question1
Write a script that presents a menu with options like "Add", "Subtract", "Multiply",
and "Divide". Based on the user's choice, perform the corresponding operation. Take the
operands from the user as well.
Code
~$ #!/bin/bash
~$
~$ # Function to display instructions
~$ display_instructions() {
> echo "Please enter your marks for the following 5th semester courses:"
>}
~$
~$ # Function to calculate GPA
~$ calculate_gpa() {
> total_marks=0
> num_courses=5
>
> for ((i=1; i<=num_courses; i++)); do
> read -p "Enter marks for course $i: " marks
> # Validate input
> while ! [[ "$marks" =~ ^[0-9]+$ ]] || [ "$marks" -lt 0 ] || [ "$marks" -gt 100 ]; do
> echo "Invalid input. Please enter a valid mark (0-100)."
> read -p "Enter marks for course $i: " marks
> done
> total_marks=$((total_marks + marks))
> done
>
> gpa=$(echo "scale=2; $total_marks / $num_courses" | bc)
> echo "Your Semester GPA is: $gpa"
>}
~$
~$ # Main loop
~$ while true; do
> display_instructions
> calculate_gpa
>
> read -p "Would you like to calculate GPA again? (yes/no): " choice
> if [[ "$choice" != "yes" ]]; then
> echo "Exiting..."
> break
> fi
> done
Output