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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
// Write a program that converts the 24-hour notation into 12-hour notation.
//14:25 shall be read as 14 25 and be converted to 2:25 PM.
//Validate the input first. Hour(s) should not be less than zero or greater than 23.
//Minutes should be between zero and 59.
#include <cstdlib>
#include <iostream>
using namespace std;
void validate(int& hours, int& mins);
//Function will display to user their 24-hours time if the time they enter doesn’t have hours
//less than zero or greater than 23 AND the minutes they enter is between zero and 59.
//Otherwise, function will prompt reentry until both valid hours and minutes are entered.
//If user enters zeros for hours and minutes the program ends.
int subtraction(int hours, int hourchange);
//Function will take the user entered 24-hours time hours and subtract 12 to get
//the 12-hours notation hours, thus new variable new_hours.
void swap_values(int& hours, int& new_hours);
//Function will swap out the 12-hours notation hours for the 24-hours time hours time.
//Swaps values stored in new_hours and hours.
void show_twelvehours(int hours, int mins);
//Function will display the 12-hours notation.
void show_twentyfourhours(int new_hours, int mins);
//Function will display the 24-hours notation.
int hours = 0;
int mins = 0;
int new_hours;
int hourchange = 12;
int main()
{
do
{ //function calls
validate(hours, mins);
new_hours = subtraction(hours, hourchange);
swap_values(hours, new_hours);
show_twelvehours(hours, mins);
show_twentyfourhours(new_hours, mins);
} while (hours != 0);
return 0;
}
//Function Definitions
void validate(int& hours, int& mins)
{
cout << "Enter a number for hours and another number for minutes." << endl;
cin >> hours;
cin >> mins;
if (hours == 0)
{
cout << "Zeros end the program." << endl;
exit(0);
}
while (hours < 0 || hours > 23)
{
cout << "Reenter hours." << endl;
cin >> hours;
}
while (mins < 0 || mins > 59)
{
cout << "Reenter minutes." << endl;
cin >> mins;
}
}
int subtraction(int hours, int hourchange)
{
new_hours = hours - hourchange;
return new_hours;
}
void swap_values(int& hours, int& new_hours)
{
int temp;
temp = hours;
hours = new_hours;
new_hours = temp;
}
void show_twelvehours(int hours, int mins)
{
if (mins < 10)
cout << "Your 12-hour time is " << hours << ":0" << mins << endl;
else
cout << "Your 12-hour time is " << hours << ":" << mins << endl;
}
void show_twentyfourhours(int new_hours, int mins)
{
if (mins < 10)
cout << "Converted back to 24-hour time is " << new_hours << ":0" << mins << endl;
else
cout << "Converted back to 24-hour time is " << new_hours << ":" << mins << endl;
}
|