Convert Minutes to Hours and Minutes

Convert Minutes to Hours and Minutes in C++

This exercise focuses on writing a simple C++ function that converts a total number of minutes into a combination of hours and remaining minutes. Time conversions are essential in applications like scheduling, event timers, and media players.

The goal is to create a function that takes an integer representing minutes and calculates how many full hours it contains, as well as the leftover minutes. For instance, 130 minutes should be displayed as 2 hours and 10 minutes.

This task helps reinforce your understanding of integer division and the modulus operator in C++.

Key Concepts

Integer Division (/)

When you divide two integers in C++, the result is the whole number of times the divisor fits into the dividend. For example, 130 / 60 equals 2.

Modulus Operator (%)

The modulus operator returns the remainder of a division. For example, 130 % 60 equals 10 (the remaining minutes).

Objective

  • 1. Define a function that takes an integer input representing total minutes.
  • 2. Use integer division to calculate the number of hours.
  • 3. Use the modulus operator to calculate the remaining minutes.
  • 4. In main(), prompt the user for input and display the converted result.

Example C++ Exercise

time_converter.cpp Basic Math
#include <iostream>

using namespace std;

// Function to convert minutes into hours and minutes
void convertToHoursAndMinutes(int totalMinutes) {
    int hours = totalMinutes / 60;   // Calculate full hours
    int minutes = totalMinutes % 60; // Calculate remaining minutes

    // Print the result
    cout << totalMinutes << " minutes is equal to " 
         << hours << " hour(s) and " 
         << minutes << " minute(s)." << endl;
}

int main() {
    int inputMinutes;

    // Prompt the user to enter the number of minutes
    cout << "Enter the number of minutes: ";
    cin >> inputMinutes;

    // Call the function to perform the conversion
    convertToHoursAndMinutes(inputMinutes);

    return 0;
}

Example Output:

Enter the number of minutes: 130
130 minutes is equal to 2 hour(s) and 10 minute(s).
Related Topics
Time Conversion C++ Integer Division Modulus Operator C++ Functions Programming Basics Math Operators C++ C++ Exercises

Share this C++ Exercise

Help others learn C++ logic!

© C++ Programming Exercises. Master the art of performance coding.