Question:5
Class Distance (km,m,cm,mm)
Declare a class named distance with attributes as km,m,cm and mm. Take input for two distances calculate and display their sum (Without using friend function).
Sol:
#include<iostream> using namespace std; class distance1 { private: int km,m,cm,mm; public: void read(); void show(); distance1 add(distance1 d); }; void distance1::read() { cout<<"Enter km, m , cm and mm "; cin>>km>>m>>cm>>mm; } void distance1::show() { cout<<km<<" km "<<m<<" m "<<cm<<" cm "<<mm<<" mm"<<endl; } distance1 distance1::add(distance1 d) { distance1 t; t.km=km+d.km; t.m=m+d.m; t.cm=cm+d.cm; t.mm=mm+d.mm; if(t.mm>=10) { t.cm=t.cm+t.mm/10; t.mm=t.mm%10; } if(t.cm>=100) { t.m=t.m+t.cm/100; t.cm=t.cm%100; } if(t.m>=1000) { t.km=t.km+t.m/1000; t.m=t.m%1000; } return(t); } int main() { distance1 e1,e2,e3; e1.read(); e2.read(); e1.show(); e2.show(); e3=e1.add(e2); e3.show(); return(0); }
Output:
Enter km, m , cm and mm 2 50 45 5
Enter km, m , cm and mm 3 56 65 6
2 km 50 m 45 cm 5 mm
3 km 56 m 65 cm 6 mm
5 km 107 m 11 cm 1 mm
Question:6
Class time (hh, mm, ss)
Declare a class named time with attributes as hh,mm and ss. Take input for two time calculate and display their sum (Without using friend function).
Sol:
#include<iostream> using namespace std; class time1 { private: int hh,mm,ss; public: void read(); void show(); time1 add(time1 d); }; void time1::read() { cout<<"Enter hh, mm and ss "; cin>>hh>>mm>>ss; } void time1::show() { cout<<hh<<" hh "<<mm<<" mm "<<ss<<" ss "<<endl; } time1 time1::add(time1 d) { time1 t; t.hh=hh+d.hh; t.mm=mm+d.mm; t.ss=ss+d.ss; if(t.ss>=60) { t.mm=t.mm+t.ss/60; t.ss=t.ss%60; } if(t.mm>=60) { t.hh=t.hh+t.mm/60; t.mm=t.mm%60; } return(t); } int main() { time1 e1,e2,e3; e1.read(); e2.read(); e1.show(); e2.show(); e3=e1.add(e2); e3.show(); return(0); }
Output:
Enter hh, mm and ss 2 50 20
Enter hh, mm and ss 4 30 45
2 hh 50 mm 20 ss
4 hh 30 mm 45 ss
7 hh 21 mm 5 ss