Good day! How are you this gloomy, rainy afternoon?
I just realized - through experimentation, naturally π - that I can return whole printf()s into main. Mind blowing. Anyway, I would much appreciate any input on how to write my leapYear function more aesthetically pleasing. I tried slapping the printf statements at the end of leapYear or at the end of each if statement. Still feels repetitive...
Also, as it stands, I'm having leapYear return int as per the declaration and definition. But I am returning printf() statements. Why does this work? I know that, for instance, char is int under the hood, using the machine's underlying character table, for instance ASCII. Is the explanaition something similar to this?
Thank you in advance! π
#include <stdio.h>
#include <string.h>
int leapYear(int year);
int main() {
int year = 0;
printf("Enter the year that you would like to check and press ENTER: ");
scanf("%d", &year);
leapYear(year);
return 0;
}
int leapYear(int year) {
char wasiswill[12] = "";
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
if (year < 2026) strcpy(wasiswill,"was");
if (year == 2026) strcpy(wasiswill, "is");
if (year > 2026) strcpy(wasiswill, "will be");
goto EXIT_LEAP;
}
else {
if (year < 2026) {
strcpy(wasiswill,"was");
goto EXIT_NLEAP1;
}
else if (year == 2026) {
strcpy(wasiswill, "is");
goto EXIT_NLEAP2;
}
else if (year > 2026) {
strcpy(wasiswill, "will not be");
goto EXIT_NLEAP3;
}
}
EXIT_LEAP: return printf("%d %s a leap year.\n", year, wasiswill);
EXIT_NLEAP1: return printf("%d %s not a leap year.\n", year, wasiswill);
EXIT_NLEAP2: return printf("%d %s not a leap year.\n", year, wasiswill);
EXIT_NLEAP3: return printf("%d %s a leap year.\n", year, wasiswill);
}
You can do the ordinal comparison once at the start instead of for both the positive and negative case. Then track a isLeap variable and just do one printf at the end with the combination of your different variables.
Your code feels repetitive now because it is. You're comparing years multiple times and printing "[not?] a leap year" multiple times.
The reason returning printf works is because the return type of printf is an int containing the count of characters printed.
I recognize that this is besides the point, but It doesn't make a ton of sense to attribute a Gregorian interpretation to years before the adoption of the Gregorian system, and thus to truly be honest in the response different leap rules ought to be used for pre-Gregorian years. In any case this will also return the wrong result for 0 or negative years as there aren't negative years or a year 0.
save