C Program to Find Age from Date of Birth
This C program calculates a person's age based on their date of birth and the current date. It accounts for months and days to provide an accurate age in years, months, and days.
Concept Overview
To calculate age, we subtract the birth date from the current date. If the current day or month is smaller than the birth day or month, we borrow days or months accordingly to ensure proper date arithmetic.
Program
C
#include <stdio.h>
int main() {
int birthDay, birthMonth, birthYear;
int currentDay, currentMonth, currentYear;
int ageYears, ageMonths, ageDays;
printf("Enter your date of birth (DD MM YYYY): ");
scanf("%d %d %d", &birthDay, &birthMonth, &birthYear);
printf("Enter current date (DD MM YYYY): ");
scanf("%d %d %d", ¤tDay, ¤tMonth, ¤tYear);
// Calculate days
if(currentDay < birthDay) {
currentDay += 30;
currentMonth -= 1;
}
ageDays = currentDay - birthDay;
// Calculate months
if(currentMonth < birthMonth) {
currentMonth += 12;
currentYear -= 1;
}
ageMonths = currentMonth - birthMonth;
// Calculate years
ageYears = currentYear - birthYear;
printf("Age: %d years, %d months, %d days\n", ageYears, ageMonths, ageDays);
return 0;
}
Sample Output
Enter birth date (dd mm yyyy): 15 5 2000 Enter current date (dd mm yyyy): 11 11 2025 Age: 25 years 5 months 27 days
Explanation
- `if (day2 < day1)` – If the current day is less than the birth day, borrow days from the previous month.
- `if (month2 < month1)` – If the current month is less than the birth month, borrow a year.
- The program then subtracts days, months, and years accordingly to find the exact age.
- `printf()` – Displays the calculated age in years, months, and days.
Note: Note: You can modify the program to automatically use the system date by using `time.h` instead of manually entering the current date.
Codecrown