Age Calculator - Hacker Challenge Solution

Let's look at the complete implementation of the age calculator program.

Below is the complete implementation of the age calculator program. Click the “Run” button to see its 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)
{
	if (day <= 0 || day > daysInAMonth(month, year))
		return false;
	else
		return true;
}

//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)
{
	if (cYear > bYear)
		return true;
	if (cYear < bYear)
		return false;
	if (cMonth > bMonth)
		return true;
	if (cMonth < bMonth)
		return false;
	if (cDay >= bDay)
		return true;
	else
		return false;
}

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;
}

void ageCalculator(int bDay, int bMonth, int bYear, int cDay, int cMonth, int cYear)
{
	int days = cDay - bDay;
	if (days<0)
	{
		cMonth--;		
		days += daysInAMonth(cMonth, cYear);
		if (days < 0)	
			//This could be possible in case of 1-31 and carry is 28/29
		{
			cMonth--;
			days += daysInAMonth(cMonth, cYear);
		}
	}
	int month = cMonth - bMonth;
	if (month<0)
	{
		cYear--;
		month += 12;
	}
	int year = cYear - bYear;
	cout << "Age is: " << year << " years " << month << " months " << days << " days " << endl;
}








Complete implementation of age calculator