Easy Tutorial
❮ C Function Strtol C Exercise Example34 ❯

C Practice Example 4

C Language Classic 100 Examples

Title: Input a specific year, month, and day, and determine which day of the year it is.

Program Analysis: Taking March 5th as an example, the days from the first two months should be added first, then add 5 days to get the day of the year. Special cases include leap years where the input month is greater than 3, requiring an additional day.

Example

#include <stdio.h>
int main()
{
    int day, month, year, sum, leap;
    printf("\nPlease enter the year, month, and day in the format: year, month, day (e.g., 2015,12,10)\n");
    scanf("%d,%d,%d", &year, &month, &day);  // Format: 2015,12,10
    switch(month) // Calculate the total days before the current month
    {
        case 1: sum = 0; break;
        case 2: sum = 31; break;
        case 3: sum = 59; break;
        case 4: sum = 90; break;
        case 5: sum = 120; break;
        case 6: sum = 151; break;
        case 7: sum = 181; break;
        case 8: sum = 212; break;
        case 9: sum = 243; break;
        case 10: sum = 273; break;
        case 11: sum = 304; break;
        case 12: sum = 334; break;
        default: printf("data error"); break;
    }
    sum = sum + day; // Add the days of the current month
    if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) { // Check if it's a leap year
        leap = 1;
    } else {
        leap = 0;
    }
    if (leap == 1 && month > 2) { // If it's a leap year and the month is greater than 2, add one more day
        sum++;
    }
    printf("This is the %dth day of the year.", sum);
    printf("\n");
}

The output of the above example is:

Please enter the year, month, and day in the format: year, month, day (e.g., 2015,12,10)
2015,10,1
This is the 274th day of the year.

C Language Classic 100 Examples

❮ C Function Strtol C Exercise Example34 ❯