adsense

Hii, welcome to my site. My name is Om prakash kartik. This blog helps you to learn programming languages concepts.

Program in C++ to calculate age Using class

Program in C++ to calculate age Using class


#include<iostream>
#include<conio.h>
 using namespace std;
  class Date
   {
     int day;
     int month;
  int year;
    public:
      Date(){
       day=1;
       month=1;
       year=2000;
     }
     void getDate()
        {
         cout<<" (day month year) :-";
         cin>>day>>month>>year;
         if(day>31)
           {
             cout<<"Invalid day!";
             exit(0);
          }
      else if(month>12)
      {
              cout<<"Invalid month!";
              exit(0);
       }
        }
   void putDate()
     {
       cout<<"\nAge is "<<year<<" years "<<month<<" months and "<<day<<" days.";
     }
   Date ageCalculate(Date &dob,Date &cd);  
};
     Date Date::ageCalculate(Date &dob,Date &cd)  
     {
      Date cal;
      int monthcode[12]={31,((dob.year%4==0&&dob.year%100!=0||dob.year%400==0||cd.year%4==0&&cd.year%100!=0||cd.year%400==0)?29:28),31,30,31,30,31,31,30,31,30,31}; 
      if(dob.day>cd.day)    //for dates 
       {
           cd.day=cd.day+monthcode[cd.month-2];
           cal.day=cd.day-dob.day;
           cd.month=cd.month-1;
          }
        else
             cal.day=cd.day-dob.day;
        if(dob.month>cd.month)  //for months 
          {
           cd.month=cd.month+12;
           cd.year=cd.year-1;
           cal.month=cd.month-dob.month;
          }
        else
          cal.month=cd.month-dob.month;    
          
        cal.year=cd.year-dob.year;//for years 
        return cal;
  }
  int main()
   {       
     Date dob,td,cal;
     cout<<"Enter date of birth";
     dob.getDate();
     cout<<"Enter current date ";
     td.getDate();
     cal=dob.ageCalculate(dob,td);
     cal.putDate();
    getch();
}
Output:-










Related Program 

Post a Comment

0 Comments