C Program to Add Days to a Given Date

This program allows the user to enter a date and a number of days to add. It calculates the resulting date while properly handling month lengths and leap years.

Concept Overview

The program repeatedly adds days to the current date. When the total exceeds the number of days in that month, it moves to the next month and adjusts the year if necessary. Leap years are considered for February.

Program

C
#include <stdio.h>

// Function to check leap year
int isLeapYear(int year) {
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
        return 1;
    return 0;
}

// Function to get number of days in a month
int daysInMonth(int month, int year) {
    int days;
    switch(month) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            days = 31;
            break;
        case 4: case 6: case 9: case 11:
            days = 30;
            break;
        case 2:
            days = isLeapYear(year) ? 29 : 28;
            break;
        default:
            days = 0;
    }
    return days;
}

int main() {
    int day, month, year, addDays;

    printf("Enter date (DD MM YYYY): ");
    scanf("%d %d %d", &day, &month, &year);

    printf("Enter number of days to add: ");
    scanf("%d", &addDays);

    day += addDays;

    while (day > daysInMonth(month, year)) {
        day -= daysInMonth(month, year);
        month++;

        if (month > 12) {
            month = 1;
            year++;
        }
    }

    printf("New Date: %02d-%02d-%04d\n", day, month, year);

    return 0;
}

Sample Output

Enter date (dd mm yyyy): 25 12 2024
Enter number of days to add: 10
New date: 4 1 2025

Explanation

  • `isLeapYear()` – Determines if a year is a leap year to handle February correctly.
  • `getDaysInMonth()` – Returns the number of days in the given month and year.
  • The loop reduces the remaining days to add by the number of days left in each month until all days are distributed.
  • `printf()` – Displays the resulting date after addition.
Note: Note: This program assumes the input date is valid. For real-world use, add validation checks for date correctness.