Write a program to accept number of seconds and display its corresponding hours, minutes and seconds

This is a simple C program that demonstrates how to convert seconds into hours, minutes, and seconds. The program takes user input for the number of seconds and then performs the necessary calculations (division & modulus) to provide the result in a human-readable format.

Tutorial 📺

Flow Chart 🌻

Let’s have a look at the flow chart.

flow chart - C Program to convert seconds into Hours, Minutes and Seconds

Code 💻

#include <stdio.h>
#include <conio.h>

void main()
  int h=0, m=0, s=0; // h-hours, m-minutes and s-seconds
  printf("Please enter the number of seconds:\n");
  scanf("%d", &s); // Input: 3663

     We know that, 1 hour = 3600 seconds
     So if we divide variable "s" by 3600, we will get hours
  h = s / 3600; // h = 3663/3600 = 1
  // Now, since we have got hours, so let's update variable "s"
  s = s % 3600; // s = 3663%3600 = 63
  // 1 minute = 60 seconds
  m = s / 60; // m = 63/60 = 1
  // Again, update variable "s"
  s = s % 60; // s = 63%60 = 3

  printf("\nHours: %d", h);
  printf("\nMinutes: %d", m);
  printf("\nSeconds: %d", s);

Explanation 🤔

  1. The program starts with the main() function by initializing three integer variables, h for hours, m for minutes, and s for seconds, all set to 0.
  2. The clrscr() function is used to clear the screen.
  3. The user is prompted to enter the number of seconds he or she wants to convert. Let’s imagine, the input in this case is 3663 seconds.
  4. Next, the conversion takes place as following:
    • h is calculated by dividing the input s by 3600 (since 1 hour is equivalent to 3600 seconds). In this example, h becomes 1.
    • The remaining seconds are obtained by taking the modulus of s by 3600, which leaves 63 seconds.
    • m is calculated by dividing the remaining seconds by 60, as 1 minute equals 60 seconds. In this case, m becomes 1.
    • The remaining seconds are again updated by taking the modulus of s by 60, resulting in 3 seconds.
  5. Finally, the program displays the converted values for hours, minutes, and seconds individually.

Categorized in:

Tagged in: