Monday, January 21, 2008
Shell program to read any year and find whether leap year or not
Pseudocode to determine whether a year is a leap year or not:
if year modulo 400 is 0 then leapA more direct algorithm:
else if year modulo 100 is 0 then no_leap
else if year modulo 4 is 0 then leap
else no_leap
if ((year modulo 4 is 0) and (year modulo 100 is not 0))
or (year modulo 400 is 0)
then leap
else no_leap
#!/bin/bash
# Shell program to read any year and find whether leap year or not
# -----------------------------------------------
# Copyright (c) 2005 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
# store year
yy=0
isleap="false"
echo -n "Enter year (yyyy) : "
read yy
# find out if it is a leap year or not
if [ $((yy % 4)) -ne 0 ] ; then
: # not a leap year : means do nothing and use old value of isleap
elif [ $((yy % 400)) -eq 0 ] ; then
# yes, it's a leap year
isleap="true"
elif [ $((yy % 100)) -eq 0 ] ; then
: # not a leap year do nothing and use old value of isleap
else
# it is a leap year
isleap="true"
fi
if [ "$isleap" == "true" ];
then
echo "$yy is leap year"
else
echo "$yy is NOT leap year"
fi
#SOLUTION 1
#Tuesday Class
#!/bin/sh
feb=`cal 2 2008`
echo $feb
lastday=`echo $feb|sed -e 's/.* //'`
if [ $lastday -eq 29 ]
then
echo "leap yr"
exit 0
else
echo "not leap yr"
exit 1
fi
#SOLUTION 2
#!/bin/sh
if cal 2 `date +%Y`|grep -q 29
then
exit 0
else
exit 1
fi
#SOLUTION 3
#!/bin/sh
feb=$(cal 2 $(date +%Y))
lastday=`echo $feb|sed -e 's/.* //'`
if [ $lastday -eq 29 ]
then
echo "leap yr"
exit 0
else
echo "not leap yr"
exit 1
fi
#SOLUTION 4
#!/bin/sh
ndays=`$(date +%j -d $(date +%Y)1231)
if [ $ndays -eq 366 ]
then
echo "leap yr"
exit 0
else
echo "not leap yr"
exit 1
fi
#SOLUTION 5
test $(date +%j -d $(date +%Y)1231) -eq 366
Subscribe to Posts [Atom]