Calculate hours, minutes and seconds for the given seconds using modulus operator of the C program

 

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional library: none/default

Additional project setting: Set project to be compiled as C

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C Code (/TC)

Other info: none

To do: Calculate hours, minutes and seconds for the given seconds using modulus operator of the C example

To show: How to use the modulus operator in C programming to calculate hours, minutes and seconds for the given seconds

 

 

// Modulus operator example in C version.

// Inputs a number of seconds, and converts to hours, minutes and seconds.

#include <stdio.h>

// #define preprocessor directive, define constants, every occurrence of the SEC_PER_MIN token in the program will be replaced with 60

#define SECS_PER_MIN 60

#define SECS_PER_HOUR 3600

 

int main(void)

{

unsigned seconds, minutes, hours, secs_left, mins_left;

 

// Prompting user to input the number of seconds

printf("Enter number of seconds: ");

 

// Read and store the data, input by user

// scanf("%d", &seconds);

scanf_s("%d", &seconds, 1);

 

// Do the modulus operations

hours = seconds / SECS_PER_HOUR;

minutes = seconds / SECS_PER_MIN;

mins_left = minutes % SECS_PER_MIN;

secs_left = seconds % SECS_PER_MIN;

 

// Display the result

printf("%u seconds is equal to ", seconds);

printf("%u hours, %u minutes, and %u seconds\n", hours, mins_left, secs_left);

 

// Return to system without any error

return 0;

}

 

Output example:

 

Enter number of seconds: 7023000

7023000 seconds is equal to 1950 hours, 50 minutes, and 0 seconds

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index