This is a C++ implementation of adding time using structures or struct. A structure is a convenient tool for handling a group of logically related data items. Structure help to organize complex data is a more meaningful way. It is powerful concept that we may after need to use in our program Design.
Write a program having a structure named Time which has three integer data items i.e. hour, minute and second. The task is to add the variables of the Time data type though a function
void AddTime(Time *time1, Time *time2)
which takes as arguments the addresses of two Time type variables, adds these variables and stores the result in time2. The function must satisfy the following:
- If second exceeds 60 then add 1 in minutes and subtract 60 from seconds.
- If minute exceeds 60 then add 1 in hours and subtract 60 from minutes.
- If hour exceeds 24 then subtract 24 from hours.
Test this function and print the result in the calling function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | // Acknowledgment: Wahib-ul-Haq #include<iostream> #include<conio.h> using namespace std; struct Time { int hour, minute, second; }; void AddTime(Time * , Time * ); int main() { Time var1, var2; for (int i = 0; i < 1; i++) { cout << "for structure variable #" << i + 1 << " Enter the hours:"; cin >> var1.hour; cout << "for structure variable #" << i + 1 << " Enter the minutes:"; cin >> var1.minute; cout << "for structure variable #" << i + 1 << " Enter the seconds:"; cin >> var1.second; cout << endl << endl; cout << "for structure variable #" << i + 2 << " Enter the hours:"; cin >> var2.hour; cout << "for structure variable #" << i + 2 << " Enter the minutes:"; cin >> var2.minute; cout << "for structure variable #" << i + 2 << " Enter the seconds:"; cin >> var2.second; } AddTime( &var1, &var2); cout << "\nNew hours = " << var2.hour; cout << "\nNew minutes = " << var2.minute; cout << "\nNew seconds = " << var2.second; cout << endl; } void AddTime(Time * time1, Time * time2) { time2 -> hour += time1 -> hour; time2 -> minute += time1 -> minute; time2 -> second += time1 -> second; if (time2 -> second > 60) { time2 -> minute += 1; time2 -> second -= 60; } if (time2 -> minute > 60) { time2 -> hour += 1; time2 -> minute -= 60; } if (time2 -> hour > 24) { time2 -> hour -= 24; } } |
Output of the C++ Program
1 2 3 4 5 6 7 8 9 10 11 12 | for structure variable #1 Enter the hours:2 for structure variable #1 Enter the minutes:10 for structure variable #1 Enter the seconds:20 for structure variable #2 Enter the hours:2 for structure variable #2 Enter the minutes:10 for structure variable #2 Enter the seconds:20 New hours = 4 New minutes = 20 New seconds = 40 |