Hacker Challenge: Age Calculator

Learn to make an age calculator program using functions.

In this lesson, we want to make an age calculator, which can calculate the age of any person up to the entered present date.

Age calculator

The program should take two dates as input and calculate age.

Sample input

Date of birth: 24 5 1997
Current date: 26 8 2017

Sample output

20 years 3 months 2 days

Let’s pause and think what the steps should be to write this program.

Main flow of the program

Jot down the steps that come to your mind, and let’s see if they match with the steps we’ve written below:

  1. We can start by taking both the current and birth dates from the user.

    • Now, what if the user enters an invalid date?

      • When we think of the dates as being valid, we mean the months should be within the valid range (1 to 12). The same goes for days (0 to 31 or 30 or 28 or even 29, as you can’t forget to check for the leap years, depending on the month entered). So we’ll need to make a function that checks the validity of the date. Let’s call this the isValidDate() function. We can make another function called daysInAMonth(), which returns the number of days in a month depending on which month it is.
    • If the user enters the wrong date, the program should take the date again.

    • To validate the current date, we also need to consider what happens if the entered current date is less than (comes before) the birth date? In such a case, the current date should again be invalid and the input should be taken again.

      • For checking if the current date is greater than the date of birth, we’ll make a function called isGreater().
  2. After validating the date, we can calculate the age by subtracting the current date from the birth date. We can perform all the calculations inside the ageCalculator() function.

Implementation of an age calculator

Let’s start with our implementation.

To calculate any person’s age, we need to know one’s date of birth and the current date.

Let’s declare our variables for both dates.

Press + to interact
int dob, mob, yob, // birth date, month, and year
cd, cm, cy, // current date, month, and year
day, month, year;

We’ll start by taking the dates as input from the user. But even when the user has entered the dates, we cannot move forward until we’ve ensured that the dates entered are valid.

Date validation checks

To ensure both dates are valid, we need to ensure the following:

  1. The days are greater than 0 and not greater than 28, 29, 30, or 31, depending on which month it is, as well as whether it’s a leap year or not.

  2. The month is not greater than 12 or less than 1.

    For example, the date 15-04-1999 is correct, and 32-13-2001 is wrong.

  3. Then, for the current date, we must ensure that it comes after the date of birth.

If the entered dates are invalid, our program should ask for valid inputs.

Press + to interact
// take date of birth from the user
do
{
cout << "Date of birth (date month year): ";
cin >> dob >> mob >> yob;
}
while (isValidDate(dob, mob, yob) == false);

In the above code, isValidDate(dob, mob, yob) is a function of return type bool that contains all the checks for the validity of the dates for all months.

We’ll apply the same to the current date.

Let’s write the implementation of the isValidDate(dob, mob, yob) function.

Press + to interact
bool isValidDate(int day, int month, int year)
{
if (day <= 0 || day > daysInAMonth(month, year))
return false;
else
return true;
}

The above function is equivalent to:

Press + to interact
bool isValidDate(int day, int month, int year)
{
return day>0 && day<= daysInAMonth(month, year);
}

In the above, daysInAMonth(month, year) is a function of return type bool that checks if a certain date is valid in that specific month or not.

Press + to interact
int daysInAMonth(int month, int year)
{
int days=0;
if (month == 4 || month == 6 || month == 9 || month == 11)
days = 30;
else if (month == 1 || month == 3 || month == 5 || month == 7
|| month == 8 || month == 10 || month == 12)
days = 31;
else if (month == 2 && year % 4 == 0)
days = 29;
else
days = 28;
return days;
}

To check the validity of the current date, we would need one more condition, namely the current date always comes after the date of birth.

1

Given the two integers, N1 and N2, in the format DDD (a three-digit number), in what order should the digits be compared to see if the first number is greater (N1 > N2)?

A)

From the least significant part to the most significant part (right to left), that is, starting with the units followed by the tens, and lastly, the hundreds.

B)

From the most significant part to the least significant part (left to right), that is, starting with the hundreds followed by the tens, and lastly, the units.

Question 1 of 20 attempted

When comparing the dates, when we compare the years and find that one date’s year is greater or lesser, we don’t need to check for the months or days. However, in case the years of the two dates are the same, we need to compare the months to know which one is greater or lesser. In case both the year and the month are the same, we need to compare the days.

So our function would be:

Press + to interact
bool isGreater(int bDay, int bMonth, int bYear, int cDay, int cMonth, int cYear) //Birth_day, Birth_Month, Birth_Year, Current_Day, Current_Month, Current_Year
{
// if current year is greater
if (cYear > bYear)
// exit the function with boolean true
return true;
// if current year is lesser
if (cYear < bYear)
// exit the function with boolean false
return false;
// if the years are same and the current month is greater
if (cMonth > bMonth)
// exit the function with boolean true
return true;
// if the years are same and the current month is lesser
if (cMonth < bMonth)
// exit the function with boolean false
return false;
/* if the years and months are same and the current day
is same or greater than the birth date */
if (cDay >= bDay)
// exit the function with boolean true
return true;
// otherwise, exit the function with boolean false
return false;
}

This is how we can compare the dates.

But hold on! We have a question for you.

Question

Could we change the above code and use if-else instead of just simple if statements? Do you think that would be more efficient?

Show Answer

Calculating age

After validating both dates, we would now like to calculate the user’s age. Suppose we have the date 28-09-2000 as the date of birth and 13-02-2017 as the current date. As you probably remember from your childhood mathematics, we start subtracting from the least significant digit (the last digit). If the subtraction of a digit yields a -ve value, then we take the carry from its adjacent higher significant digit and proceed.

For example, suppose we want to do the following subtraction 871798871 - 798:

Understand the above animation carefully. How do we subtract? We subtract from right to left. Why? The reason for going from right to left is that first, we need to subtract the least significant digit. If that subtraction is not possible, we take a carry from the neighboring higher significant digit, which is equivalent to 10 units of the current position. This process is called taking a carry from the neighbor.

In age calculation, the least significant digits are the days (the date itself) and the most significant digits are the years in the date. So we will start our subtraction with days, and then we will move to months and then years. For example, we have:

Current date: 13-02-2017
Date of birth: 28-09-2000

We can not subtract days because 13 is less than 28, so we will take carry from months. As the previous month is January (Think! Why have we not taken carry from February? Hint: Has February ended or is it still going on?) and it has 31 days, we will add 31 in 13, which will be 44. Now our days will be (4428=1644-28=16). We have the same situation with months, that is, we can not subtract 9 from 1. We will take carry from the year, adding 12 in 1, which will be 13. Now our months will be (139=413-9=4), and the years can be subtracted easily (20162000=162016-2000=16). Finally, we have the age, which is 16 years, 4 months, and 16 days.

Let’s watch the animation for the above scenario:

While writing the code, we need to remember that if we want a carry from the previous month and that month is January, then we will add 31 to days (because January has 31 days). If it is April, then we will add 30 (because April has 30 days).

Let’s make a function for age calculation called ageCalculator().

This function will take the parameters int bDay, int bMonth, int bYear, int cDay, int cMonth, int cYear.

First, we will subtract days (cDay - bDay). If this subtraction gives a negative answer (less than zero), then we will take a carry from cMonth, which will add 28, 29, 30, or 31 (depending on which month it is).

Note that the carry of the number of days must be from the previous month because the current month has not yet passed and the previous month has passed.

When we subtract months (cMonth - bMonth), it might also give a negative answer. In such a case, we will take a carry again from cYear. It will add 12 in months.

Lastly, we will subtract Years (cYear - bYear).

Now that we’ve discussed the working of the ageCalculator() function, we are ready to implement the age calculator program.

From all that we’ve discussed in this lesson, add the code inside the functions in the editor below and complete the program. Then click “Run” to see the output.

#include <iostream>
using namespace std;
//This function is simply checking dates.
bool isValidDate(int day, int month, int year);
int daysInAMonth(int month, int year);
//This function is comparing both dates and validating them.
bool isGreater(int bDay, int bMonth, int bYear, int cDay,
						int cMonth, int cYear);
//This function is calculating age.
void ageCalculator(int bDay, int bMonth, int bYear, 
                       int cDay, int cMonth, int cYear);
int main()
{
	int dob, mob, yob; //date of birth, month of birth, year of birth
	int cd, cm, cy;   //current date, current month, current year
	do
	{
		cout << "Date of birth (day month year): ";
		cin >> dob >> mob >> yob;
	} 
            while (isValidDate(dob, mob, yob) == false);
	do
	{
		cout << "Current date (day month year): ";
		cin >> cd >> cm >> cy;
	} 
    while (isValidDate(cd, cm, cy) == false 
	    		|| isGreater(dob, mob, yob, cd, cm, cy) == false);
	
	ageCalculator(dob, mob, yob, cd, cm, cy);
	return 0;
}
bool isValidDate(int day, int month, int year)
{
	// Add code here.
}

//Birth_day,Birth_Month,Birth_Year,Current_Day,Current_Month,Current_Year
bool isGreater(int bDay, int bMonth, int bYear, 
                   int cDay, int cMonth, int cYear)
{
	// Add code here.
}

int daysInAMonth(int month, int year)
{
	// Add code here.
}

void ageCalculator(int bDay, int bMonth, int bYear, int cDay, 
                                       int cMonth, int cYear)
{
	// Add code here.

	cout << "Age is: " << year << " years " << month << " months " 
	<< days << " days " << endl;
}


Add code in the age calculator program