How to resolve the algorithm Leap year step by step in the Bash programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Leap year step by step in the Bash programming language

Table of Contents

Problem Statement

Determine whether a given year is a leap year in the Gregorian calendar.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Leap year step by step in the Bash programming language

Source code in the bash programming language

#!/bin/bash

is_leap_year ()  # Define function named is_leap_year
{

declare -i year=$1      # declare integer variable "year" and set it to function parm 1

echo -n "$year ($2)-> " # print the year passed in, but do not go to the next line

if (( $year % 4 == 0 )) # if year not dividable by 4, then not a leap year, % is the modulus operator 
then
        if (( $year % 400 == 0 ))       # if century dividable by 400, is a leap year
        then
                echo "This is a leap year"
        else
                if (( $year % 100 == 0 )) # if century not divisible by 400, not a leap year
                then
                        echo "This is not a leap year"
                else
                        echo "This is a leap year" # not a century boundary, but dividable by 4, is a leap year
                fi
        fi
else
        echo "This is not a leap year"
fi


}

# test all cases
# call the function is_leap_year several times with two parameters... year and test's expectation for 'is/not leap year.
is_leap_year 1900 not # a leap year
is_leap_year 2000 is  # a leap year
is_leap_year 2001 not # a leap year
is_leap_year 2003 not # a leap year
is_leap_year 2004 is  # a leap year

# Save the above to a file named is_leap_year.sh, then issue the following command to run the 5 tests of the function
# bash is_leap_year.sh


  

You may also check:How to resolve the algorithm Active object step by step in the Nim programming language
You may also check:How to resolve the algorithm Dining philosophers step by step in the Visual Basic .NET programming language
You may also check:How to resolve the algorithm XML/Input step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Penney's game step by step in the 11l programming language
You may also check:How to resolve the algorithm Execute a system command step by step in the Perl programming language