Worked-out Examples

This pages contains few worked-out examples for you to practice!

  1. Read a 5 digit number and print it in reverse. Check if the input is 5 digit positive number

#!/bin/bash

# Function to reverse a number
reverse_number() {
    local num=$1
    local reversed=0
    while [ $num -ne 0 ]; do
        reversed=$((reversed * 10 + num % 10))
        num=$((num / 10))
    done
    echo "$reversed"
}

# Read input
read -p "Enter a 5-digit positive number: " input_num

# Validate input
if [[ $input_num =~ ^[0-9]{5}$ ]]; then
    # Convert to integer
    input_num=$((input_num))

    # Reverse the number
    reversed=$(reverse_number "$input_num")

    # Print result
    echo "The reversed number is: $reversed"
else
    echo "Invalid input. Please enter a 5-digit positive number."
fi
  1. Read two input values, equate them to two variables and perform the swap

  1. Read a non-zero input number and check if it is a palindrome

  1. Reverse an input number with out using a Loop

  1. Read a 10 digit number as input, identify even digits, odd digits and digits that are prime numbers by splitting the input number

  1. Read .txt files from the working directory and print the file names in alphabetic order

  1. Read the .txt files from the working directly and print the file names by modification date

  1. Read the .txt files from the input directory and print the file names by modification date

  1. A calculator program with two non negative intergers as input

  1. Provide a square root and cube root of a number

  1. Read a 10 digit number as input, reverse it and check if each digit is divisible by 2

  1. Read a paragraph as input and identify number of vowels are present in the paragraph

  1. Read the paragraph as input and identify number of consonants are present in the paragraph

  1. Convert the current date-time into EST, PST, MST, CST Timezone

  1. Calculate the Age of a person in years, month, days when his/her birth date is provided as input

  1. Provide a date as input and return the "day" of date in a respective week along with the week number in that given year.

Last updated