Thread: Convert seconds to hours, minutes and seconds

  1. #1
    Registered User
    Join Date
    May 2011

    Convert seconds to hours, minutes and seconds


    I've written the following code to convert time in seconds to time in hours, minutes and seconds. The time in seconds is stored in the variable total, there's no user input yet. Is my code simple or is there a simpler or faster way to write the code?

    #include <stdio.h>
    #define NROFITEMS 3
    int values[NROFITEMS] = {3600, 60, 1};
    int count[NROFITEMS];
    char *names[NROFITEMS] = {"hours", "minutes", "seconds"};
    int main (int argc, const char * argv[])
        int i, total = 6789;
        for (i = 0; i < NROFITEMS; ++i) {
            count[i] = total / values[i];
            total -= count[i] * values[i];
        for (i = 0; i < NROFITEMS; ++i) {
            printf("\n%s: %i", names[i], count[i]);
        return 0;

  2. #2
    Registered User
    Join Date
    Jun 2011
    Well, you could move the "printf()" statement in the second "for()" loop into the first "for()" loop.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Long Beach, CA
    total -= count[i] * values[i];
    could just be
    total %= values[i];
    I'm not sure that the run time will change much, but IMO, the code will be a little easier to understand.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. hour,minutes & seconds
    By anaer0bic in forum C Programming
    Replies: 14
    Last Post: 06-28-2011, 11:19 AM
  2. Replies: 12
    Last Post: 10-05-2009, 12:19 AM
  3. Converting seconds to hours in decimal form?
    By ajmcello in forum C Programming
    Replies: 3
    Last Post: 04-24-2006, 02:35 AM
  4. Algo for create hours and minutes with given seconds
    By BianConiglio in forum C Programming
    Replies: 6
    Last Post: 05-30-2004, 06:50 PM
  5. Converting MInutes to Hours and MInutes
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 08-30-2001, 08:07 PM
Website Security Test