Tuesday, April 16, 2013

Time Class Using Operator Overloading


Objective:
Write a program to add time given in hours , minutes and seconds by using operator overloading.

Program:

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

namespace ConsoleApplication1
{
    class Time
    {
        int hour;
        int minute;
        int second;

        public Time(int hh, int mm, int ss)
        {
            hour = hh;
            minute = mm;
            second = ss;
        }
        public void Display()
        {
            Console.WriteLine("The Total Time is {0} hour, {1} minute ,{2} seconds", hour, minute, second);
        }
        public static Time operator +(Time ft, Time st)
        {
            int h, m, s;

            h = ft.hour + st.hour ;
            m = ft.minute + st.minute;
            s = ft.second + st.second;
            if (m > 59)
            {
                for (int a = m; a > 59; m -= 60)
                {
                    h++;
                    if (s > 59)
                    {
                        for (int c = s; c > 59; s-=60 )
                        {
                            m++;
                        }
                   
                    }
                }
            }      
           
            Time T = new Time(h, m, s);
            return T;
        }


        static void Main(string[] args)
        {
            Time T1 = new Time(12, 150, 250);
            Time T2 = new Time(5, 200, 200);
            Time T3 = T1 + T2;
            T3.Display();
        }
    }
}

Output:


No comments:

Post a Comment