Tuesday, April 16, 2013

Operator Overloading in C# Class of Weight


Objective:
Write a program to add weight given in kilogram, gram and miligram by using operator overloading.

Program:

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

namespace ConsoleApplication1
{
    class weight
    {
        int kilogram;
        int gram;
        int milligram;

        public weight(int kg, int g, int mg)
        {
            kilogram = kg;
            gram = g;
            milligram = mg;
        }
        public void Display()
        {
            Console.WriteLine("The Total weight is {0} kilogram, {1} gram ,{2} milligram", kilogram, gram, milligram);
        }
        public static weight operator +(weight fd, weight sd)
        {
            int kgg, gg, mgg;

            kgg = fd.kilogram + sd.kilogram;
            gg = fd.gram + sd.gram;
            mgg = fd.milligram + sd.milligram;

            if (mgg > 9)
            {
                for (int n = mgg; mgg > 9; mgg -= 10)
                {
                    gg++;

                    if (gg > 999)
                    {
                        for (int a = gg; gg > 999; gg -= 1000)
                        {
                            kgg++;
                        }
                    }
                }
            }



            weight w = new weight(kgg, gg, mgg);
            return w;
        }


        static void Main(string[] args)
        {
            weight w1 = new weight(12, 1500, 25);
            weight w2 = new weight(25, 3665, 20);
            weight w3 = w1 + w2;
            w3.Display();
        }
    }
}

Output:


No comments:

Post a Comment