C++ Programming

Program Distance with Data Members Meter, Centimeter and Kilometer

Write a Program defining a class named distance with data members meter, centimeter and kilometer. Introduce member functions get_data (), show_data () and function to add two objects of class distance and returning object. Use reference arguments in the function for addition.

Source Code:

#include<iostream.h>
#include<conio.h>
class distance
{
   public:
   float km,m,cm;
   void get_data()
      {
               cout<<"Enter kilometers: ";
               cin>>km;
         cout<<"Enter meters: ";
               cin>>m;
         cout<<"Enter centimeters: ";
               cin>>cm;
      }
      void show_data()
      {
               cout<<"\nKilometers: "<<km<<endl;
         cout<<"Meters: "<<m<<endl;
         cout<<"Centimeters: "<<cm<<endl;
      }
};
distance d;
float a=0,b=0,c=0,o=0;
float add(distance &d)
{
              a=a+d.km;
   b=b+d.m;
   c=c+d.cm;
   if(c>100)
   {
               c=c-100; b=b+1;
   }
   if(b>1000)
   {
               b=b-1000; a=a+1;
   }
   o=(a+(b/1000)+(c/10000));
   return o;
}
void main()
{
               cout<<"Enter first value of distance: \n";
               d.get_data();
      add(d);
   cout<<"\nThe entered value is: \n";
               d.show_data();
   cout<<"\nEnter second value of distance: \n";
               d.get_data();
   cout<<"\nThe entered value is: \n";
               d.show_data();
   cout<<"\nThe summed value of distance in kilometer is: "<<add(d);
   getch();
}
Back to top button