Pages

100 Contemporary Living Room Designs

Sunday, September 9, 2012

C++ PROGRAM TO CONVERT TIME FROM 24-HR TO 12-HR FORMAT USING FRIEND CLASS AND PARAMETERISED CONSTRUCTOR.

Create a class time that has separate int member data for hours, minutes and seconds in which time is represented in 24-hr format. One constructor should initialize this data to zero and another constructor initialize it to fixed values. Another class is created to represent time in 12-hr format. A member function must be defined to convert 24-hr format to 12-hr format. A main() program should create objects of class time, read time in 24-hr format and convert it in to 12-hr format. 



#include<iostream.h>
#include<string.h>
#include<conio.h>
class time24
{
  int hours,minutes,seconds;
  public:
  time24()
  {
    hours=minutes=seconds=0;
  }
  time24(int h,int m,int s)
  {
    hours=h;
    minutes=m;
    seconds=s;
  }
  void display()
  {
    if(hours<10)
    cout<<'0';
    cout<<hours<<":";
    if(minutes<10)
      cout<<'0';
    cout<<minutes<<":";
    if(seconds<10)
      cout<<'0';
    cout<<seconds;
  }
  friend class time12;
};
class time12
{
  int pm;
  int hour,minute;
  char *am_pm;
  public:
  time12(time24);
  void display()
  {
    cout<<hour<<":";
    if(minute<10)
      cout<<'0';
    cout<<minute<<" ";
    cout<<am_pm;
  }
};
time12::time12(time24 t24)
{
  int hrs24=t24.hours;
  int pm=t24.hours<12 ? 0:1;
  int min=t24.seconds<30 ? t24.minutes:t24.minutes+1;
  if(min==60)
  {
    min=0;
    ++hrs24;
    if(hrs24==12 || hrs24==24)
    pm=(pm==1)? 0:1;
  }
  int hrs12=(hrs24<13) ? hrs24 : hrs24-12;
  if(hrs12==0)
  {
    hrs12=12;
    pm=0;
  }
    if(pm==1)
    {
      am_pm=" pm";
    }
    else
    {
      am_pm=" am";
    }

    hour=hrs12;
    minute=min;
}
int main()
{
  clrscr();
  int h1,m1,s1,x=1;
  while(x==1)
  {
    cout<<"enter 24-hour time:\n";
    cout<<"Hours(0-23):";
    cin>>h1;
    if(h1>23)
    return(1);
    cout<<"Minutes:";
    cin>>m1;
    cout<<"Seconds:";
    cin>>s1;
    time24 t24(h1,m1,s1);
    cout<<"you entered:";
    t24.display();
    cout<<endl;
    time12 t12=t24;
    cout<<"\n12-hour time:\n";
    t12.display();
    cout<<endl;
    x=0;
  }
  getch();
  return 0;
}

OUTPUT


No comments:

Post a Comment