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 commonly used in many applications such as scheduling, event timers, and media players. Understanding how to divide and use the modulus operator will be essential in this task.

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 exercise helps reinforce your understanding of integer division, the modulus operator, and basic function implementation in C++.

Group

Functions in C++

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 the main function, ask the user for input and display the result using the conversion function.

Write a function that converts minutes to hours and minutes.

Example C++ Exercise

 Copy C++ Code
#include <iostream> // Include the iostream library for input and output

using namespace std; // Use the standard namespace

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

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

// Main function
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; // End of the program
}

 Output

Enter the number of minutes: 130
130 minutes is equal to 2 hour(s) and 10 minute(s).

Share this C++ Exercise


More C++ Programming Exercises of Functions in C++

Explore our set of C++ Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C++. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in C++.