Define a Date type and compute the day of the year (with leap years) and the number of days between two dates in the same year.
Solution
main.c
#include <stdbool.h>
#include <stdio.h>
typedef struct {
int day, month, year;
} Date;
static bool is_leap(int y) { return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; }
int day_of_year(Date d) {
static const int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int n = d.day;
for (int m = 1; m < d.month; m++)
n += days[m - 1] + (m == 2 && is_leap(d.year));
return n;
}
int main(void) {
Date a = {15, 8, 2024}, b = {1, 3, 2026}, c = {15, 8, 2026};
printf("15/08/2024 is day %d\n", day_of_year(a));
printf("01/03/2026 is day %d\n", day_of_year(b));
printf("days from 01/03/2026 to 15/08/2026: %d\n", day_of_year(c) - day_of_year(b));
return 0;
}
Output Verified by compiling and running
15/08/2024 is day 228
01/03/2026 is day 60
days from 01/03/2026 to 15/08/2026: 167
The month lengths live in a const table, and February gets one extra day in leap years (the bool adds 0 or 1). 2024 is a leap year, so 15 August is day 228 instead of 227.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!