Midterm Sample

ALL TASKS ARE OBLIGATORY

Create the below-given tasks in Bash and upload the solutions to Canvas. You have altogether 60 minutes for the work and the upload. There is extra 5 minutes, but each minute delay will cause minus 2 points from the points sum. Each task values 5 points if it they are perfect. No points for solutions with syntax errors.

Task 1

Task

Create a Bash Script to evaluate the sum of even numbers stored in a file. Take the file as a parameter. Numbers in the file are below:

8
2
3
4

Output: 14

Solution

#!/bin/bash
 
file="$1"
sum=0
 
if [[ ! -f "$file" ]]; then
    echo "Error: File not found"
    exit 1
fi
 
while read -r num; do
    if (( num % 2 == 0 )); then
        (( sum += num ))
    fi
done < "$file"
 
echo "$sum"

Task 2

Task

Create a Bash Script that adds the numbers of two columns and multiplies them by the numbers of the third column. Take the file as a parameter. Data in the file are below:

1 2 3
4 5 6
7 8 9

Output:

9      # (1+2)*3
54     # (4+5)*6
135    # (7+8)*9

Solution

#!/bin/bash
 
file="$1"
 
if [[ ! -f "$file" ]]; then
    echo "Error: File not found"
    exit 1
fi
 
while read -r col1 col2 col3; do
    sum=$(( col1 + col2 ))
    result=$(( sum * col3 ))
    printf "%d\n" "$result"
done < "$file"

Task 3

Task

Create a Bash Script that check if the numbers is Armstrong or not. Take a number as parameter. Input: 153 Output: True #1^3+3^3+5^3=153

Solution

#!/bin/bash
 
num="$1"
original="$num"
power=3  # For 3-digit numbers
temp="$num"
sum=0
 
## Calculate sum of cubes
while (( temp > 0 )); do
    digit=$(( temp % 10 ))
    (( sum += digit ** power ))
    (( temp /= 10 ))
done
 
if (( sum == original )); then
    echo "True #${original}^3+5^3+3^3=${original}"
else
    echo "False"
fi

Task 4

Task

Create a Bash Script to determine the maximum value among three numbers. Take three numbers from keyboard as variables.

Solution

#!/bin/bash
 
echo "Enter first number: "
read -r num1
echo "Enter second number: "
read -r num2
echo "Enter third number: "
read -r num3
 
max=$num1
 
if (( num2 > max )); then
    max=$num2
fi
 
if (( num3 > max )); then
    max=$num3
fi
 
echo "Maximum value: $max"

0 items under this folder.