Error in the Mini-Calender project in C

I have almost just started the project and am getting an error with the following code.
The programme is finding out whether or not it is a leap year.

The condition in summary is this;
A leap year has to be divisible by 4 and NOT divisible by 100 except when the year is divisible by 400.

A brief personal description is this;
When a year is divisible by 4, it is a leap year and the function has to evaluate to true. While already in the scope of what I just mentioned above, when it is not divisible by 100, it is still a leap year, but when it is divisible by

#include <stdio.h>
#include <stdbool.h>
bool is_leap_year(int year) {
  if((year % 4) != 0){
    return false;
  } else {
    return true;
    if((year % 100) != 0){
      return true;
    } else {
      if((year % 400) != 0){
        return false;
      } else {
        return true;
      }
    }
  }

}

int main() {
  int year = 1992;
  int year_status = is_leap_year(year);
  
  if (year_status == true)
      printf("This is a leap year\n");
  printf("This is not a leap year\n");
}

Unfortunately when I run the code, it returns both options like this;
This is a leap year
This is not a leap year

Hello @joshuamwesigwa !

Hope this isn’t too delayed but it is because you return true if ((year % 4) != 0). When you return a value to a function, it breaks out of the function (because it is finished with its task) and the rest of the code doesn’t run. Another thing to take note of is the precedence so that you won’t have to use too many nested if else statements (it downgrades readability). So at best you only need three if statements (if, elseif, and else). Or you can do one and write everything on one line, but I think the if statements might help better with understanding.

Leap year == true if (year % 4 == 0 && (year % 100 != 0) EXCEPT if (year % 400 == 0)). So this means that year % 400 == 0 has top priority because only then can you check if year % 100 != 0. if that is false, then you check if (year % 4 == 0 && year % 100 != 0). If the year doesn’t fulfill these two conditions, then you use a default (else).

if (year % 400 == 0) {
   return true;
} else if (year % 4 == 0 && year % 100 != 0) {
   return true;
} else {
   return false;
}

*** The reason why you have two option is because you have two printf statements, since 1992 % 4 == 0, it returns true causing your if statement in your main func to run. Then you have a printf statement outside that prints that it is not one without any condition. You need an else with it, you can also reduce it to:

if (year_status) { // this means if true but you can use year_status == true as well
   ...
} else {
   ...
}

So technically your code is working in this case, but doesn’t work in general because if you put 1000 as the year, it will return true even though it is false.

1 Like