Connecting Tech Pros Worldwide Forums | Help | Site Map

Leap year C shell script

Newbie
 
Join Date: Jan 2008
Posts: 5
#1: Feb 29 '08
Hello. So im a little bit stuck on one of my homework questions.
heres the question:

Write a C Shell Script that performs the following functions. Asks the user to input a year. The script should then calculate whether or not the year is a leap year. The script should caculate whether or not it is a leap year using the following algorithm. A leap year is defined as any year divisible by 4 but not by 100. However, if a year is divisible by 4 and by 100, it is not a leap year unless it is also divisible by 400. The script should implement the math to produce this algoritm and tell the user whether or not the year entered is a leap year.

heres what i have so far:
************************************************** ***********
#!/bin/csh

echo Please input a year
set year = $<

if ( $year / 4 ) then
echo this is a leap year
else
echo this is not a leap year
endif

************************************************** **********

i know its not exactly what the teacher wanted but i was just messing around with it to see if this could tell me whether or not it was a leap year and for every year i input it tells me its a leap year. i dont know what im doing wrong. any help would be helpful thanks

Newbie
 
Join Date: Mar 2008
Posts: 14
#2: Mar 30 '08

re: Leap year C shell script


The problem here is the expression if ( $year / 4 ). This test will return true as long as it is a valid division, which in this case is true for all values of $year. What you want is a test that returns true when the division does not give any remainder. You can use the modulo operator for this:
Expand|Select|Wrap|Line Numbers
  1. if ( $year % 4 == 0)
Nepomuk's Avatar
Moderator
 
Join Date: Aug 2007
Location: Germany
Posts: 2,466
#3: Apr 8 '08

re: Leap year C shell script


Also, your algorithm isn't quite correct - check http://en.wikipedia.org/wiki/Leap_year#Algorithm for a correct algorithm in pseudocode.

Greetings,
Nepomuk
Newbie
 
Join Date: Apr 2008
Location: India
Posts: 1
#4: Apr 8 '08

re: Leap year C shell script


if ((( $year % 4 == 0) && ( $year % 100 != 0)) || $year % 400 == 0 )
echo "Leap Year";
else
echo "Not a leap year";
Expert
 
Join Date: Sep 2007
Posts: 856
#5: Apr 8 '08

re: Leap year C shell script


We don't spoonfeed code here. Read these Posting Guidelines and you'll understand why.
Reply