186k views
5 votes
Write a program that reads from user (i) an hour between 1 to 12 and (ii) number of hours ahead. The program should print the time after those many hours

1 Answer

3 votes

Answer:

The cpp program for time calculation is given below.

#include <iostream>

using namespace std;

int main()

{

// variables declared but not initialized

int hour;

int hrs_ahead;

int time;

cout<<" Enter an hour between 1 to 12: ";

cin>>hour;

cout<<" Enter the required number of hours ahead: ";

cin>>hrs_ahead;

time = hour + hrs_ahead;

//time is adjusted to display correct time in 12 hour format

if(time > 12)

time = time - 12;

//final time is displayed to the console

cout<<" The time after "<< hrs_ahead <<" hours is "<< time <<endl;

//any integer can be returned but 0 is a standard practice

return 0;

}

OUTPUT

Enter an hour between 1 to 12: 11

Enter the required number of hours ahead: 5

The time after 5 hours is 4

Step-by-step explanation:

The program is described below.

1. The variables are declared to hold the three values, i.e., current hour, hours ahead and the final time. The variables are declared as integers since complete hour is to be stored.

2. User input is taken for both the current hour and hours ahead.

3. The final time is calculated by adding both the user inputs. The 12-hour time format is followed hence, the final time to be displayed is between 1 to 12.

4. The final time is displayed and a new line is inserted at the end.

5. No validation is done for user input as per the requirement.

6. The output is displayed using keyword, cout.

7. The input is taken using keyword, cin.

8. All the code is written inside main() having return type integer.

9. The program ends with a return statement.

10. New line is inserted using the keyword, endl.

11. The cpp language is not purely object oriented language hence use of classes is not mandatory.

12. The variables can also be declared at the beginning of the program and outside main() and any other methods created in the program.

User Maxim Popov
by
6.3k points