Leap year C shell script

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jrw133
    New Member
    • Jan 2008
    • 5

    Leap year C shell script

    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
  • oberon
    New Member
    • Mar 2008
    • 14

    #2
    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:
    Code:
    if ( $year % 4 == 0)

    Comment

    • Nepomuk
      Recognized Expert Specialist
      • Aug 2007
      • 3111

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

      Greetings,
      Nepomuk

      Comment

      • afixibiranchi
        New Member
        • Apr 2008
        • 1

        #4
        Calculating leap year

        if ((( $year % 4 == 0) && ( $year % 100 != 0)) || $year % 400 == 0 )
        echo "Leap Year";
        else
        echo "Not a leap year";

        Comment

        • Laharl
          Recognized Expert Contributor
          • Sep 2007
          • 849

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

          Comment

          Working...