Tuesday, April 16, 2013

Distance Class in C#


Objective:
Write a program to add distance give in meter, kilometer, and centieter by using operator overloading method.

Program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Distance
    {
        int kilometer;
        int meter;
        int centimeter;

        public Distance(int km, int m, int cm)
        {
            kilometer = km;
            meter = m;
            centimeter = cm;
        }
        public void Display()
        {
            Console.WriteLine("The Total Distance is {0} kilometer, {1} meter ,{2} centimeter", kilometer, meter, centimeter);
        }
        public static Distance operator +(Distance fd, Distance sd)
        {
            int km, m, cm;

            km = fd.kilometer + sd.kilometer;
            m = fd.meter + sd.meter;
            cm = fd.centimeter + sd.centimeter;

            if(m > 999)
            {
                for (int n = m; m > 999;m-=1000 )
                {
                    km++;

                    if (cm > 99)
                    {
                        for (int a = cm; cm > 99; cm-=100 )
                        {                           
                            m++;
                        }
                    }
                }
            }



            Distance d = new Distance(km, m, cm);
            return d;
        }


        static void Main(string[] args)
        {
            Distance d1 = new Distance(18, 1000, 18020);
            Distance d2 = new Distance(25, 2000, 250);
            Distance d3 = d1 + d2;
            d3.Display();
        }
    }
}

Output:


No comments:

Post a Comment