LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   I don't know how to solve a problem in C (https://www.linuxquestions.org/questions/programming-9/i-dont-know-how-to-solve-a-problem-in-c-207212/)

nostrum 07-19-2004 10:02 PM

I don't know how to solve a problem in C
 
Hi I'm working through the programming exercises in my Practical C Programming 3rd Ed, and I'm having trouble even creating a formula to solve the problem. The problem is as follows:

A leap year is any year divisible by 4, unless the year is divisible by 100, but not 400. Write a program to tell if a year is a leap year.

Now at first I thought by possibly using the if() statement I could figure this out and the if() statement still might suffice, but it appears I need to tell whether the condition is positive or false aka whether the year is divisble by 100 but not 400. I just don't know how to do that and I was wondering if someone could either show me how or point me in the right direction. Any help would be greatly appreciated. Thanks again to all the cool folks who've helped me in the past.

-Spiros Vondas

rgiggs 07-19-2004 10:15 PM

how about this?

Code:

  if (divisible by 4)
    if (not divisible by 100)
      leap
    else
      if (divisible by 400)
        leap
      else
        non leap
  else
    non leap;


nostrum 07-19-2004 10:39 PM

Thanks....
 
Does leap need anything after it or need meet any conditions? I've never seen ti used before and am having trouble find out information on it.
-Spiros

osvaldomarques 07-19-2004 11:20 PM

For you to check this divisibility all you need is check for remainder == 0; So, instead of "/" you need to use "%"
Code:

if (given_year % 4 == 0 && (given_year % 100 != 0 || given_year % 400 == 0)) // leap year

nostrum 07-20-2004 12:56 AM

WOOHOO!
 
Thank you so much that's exactly what I needed I appreciate it!
-Spiros Vondas

Hko 07-20-2004 07:57 AM

Short one, just for fun:
Code:

if ((!(y%4)&&y%100)||!(y%400)) {
    /* y is leap */
}

<edit>
Hmm, after reading the thread a second time, mine is not that much shorter actually (apart from the var-name for the year)
</edit>


All times are GMT -5. The time now is 09:14 PM.