Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
C program to calculate age
Calculating age is a common programming task that requires handling date arithmetic carefully. This involves computing the difference between two dates while accounting for varying month lengths and leap years.
Syntax
void calculateAge(int currentDay, int currentMonth, int currentYear,
int birthDay, int birthMonth, int birthYear);
Algorithm
The age calculation follows these steps −
- If the current day is less than birth day, borrow days from the previous month
- If the current month is less than birth month, borrow 12 months from the previous year
- Subtract birth date from current date to get the final age
Example
This program calculates age by handling date borrowing logic ?
#include <stdio.h>
void calculateAge(int currentDay, int currentMonth, int currentYear,
int birthDay, int birthMonth, int birthYear) {
int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/* Handle day borrowing */
if (birthDay > currentDay) {
currentDay += daysInMonth[birthMonth - 1];
currentMonth--;
}
/* Handle month borrowing */
if (birthMonth > currentMonth) {
currentYear--;
currentMonth += 12;
}
int ageYears = currentYear - birthYear;
int ageMonths = currentMonth - birthMonth;
int ageDays = currentDay - birthDay;
printf("Present Age<br>");
printf("Years: %d Months: %d Days: %d<br>", ageYears, ageMonths, ageDays);
}
int main() {
int currentDay = 21;
int currentMonth = 9;
int currentYear = 2019;
int birthDay = 25;
int birthMonth = 9;
int birthYear = 1996;
printf("Current Date: %d/%d/%d<br>", currentDay, currentMonth, currentYear);
printf("Birth Date: %d/%d/%d<br>", birthDay, birthMonth, birthYear);
calculateAge(currentDay, currentMonth, currentYear,
birthDay, birthMonth, birthYear);
return 0;
}
Current Date: 21/9/2019 Birth Date: 25/9/1996 Present Age Years: 22 Months: 11 Days: 26
How It Works
The calculation works by handling two key scenarios:
- Day Adjustment: When birth day is greater than current day, we add days from the previous month and reduce the month by 1
- Month Adjustment: When birth month is greater than current month, we add 12 months and reduce the year by 1
- Final Calculation: Subtract birth values from adjusted current values to get precise age
Key Points
- This algorithm handles all edge cases including month-end dates
- The
daysInMonth[]array provides correct days for each month - Leap year considerations can be added for February if needed
Conclusion
This program accurately calculates age by handling date arithmetic with proper borrowing logic. The method works for all valid date combinations and provides results in years, months, and days format.
Advertisements
