Complementary task for topic: 1

M Nemeth · 2023-08-29 15:21:04.600220'

Printf: Time conversion

Printf: Time conversion

Print the number of hours, minutes, and seconds in a given time in seconds
e.g. total seconds: 3665
The program output:
Time: 01 hours, 01 minutes, 05 seconds.

Hint: Use %d for decimal print
Use %02d for get the two digit format
Use the modulo (%) operator to get the reaminers!

Solution
#include 

int main() {
    int totalSeconds = 3665; // Example: 3665 seconds
    
    int hours = totalSeconds / 3600;
    int minutes = (totalSeconds % 3600) / 60;
    int seconds = totalSeconds % 60;
    
    printf("Time: %02d hours, %02d minutes, %02d seconds.\n", hours, minutes, seconds);
    
    return 0;
}


Explanation
In this example, we have a predefined integer variable totalSeconds set to 3665. The program calculates the equivalent number of hours, minutes, and seconds from the given time in seconds. The result is stored in the variables hours, minutes, and seconds. Then, it uses printf() to display the result with the specified format.

When you run the program, it will output the time in hours, minutes, and seconds using printf() as specified in the task. The %02d format specifier is used to print integers with a minimum width of two digits, padded with leading zeros if necessary.







< < previous    next > >