Convert seconds to hours, minutes and seconds

This is a discussion on Convert seconds to hours, minutes and seconds within the C Programming forums, part of the General Programming Boards category; Hello, I've written the following code to convert time in seconds to time in hours, minutes and seconds. The time ...

  1. #1
    kkk
    kkk is offline
    Registered User
    Join Date
    May 2011
    Posts
    32

    Convert seconds to hours, minutes and seconds

    Hello,

    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?


    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
    Posts
    2,292
    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
    Location
    Long Beach, CA
    Posts
    5,467
    Code:
    total -= count[i] * values[i];
    could just be
    Code:
    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

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21