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

Convert seconds into its corresponding hours, minutes and seconds is pretty easy, if you understand how division and modulo operations work.

Tutorial πŸ“Ί

Watch tutorial and learn how to solve this problem. πŸ˜‰

Steps πŸͺœ

To Convert seconds into corresponding hours, minutes and seconds

  1. Accept an integer from the user and store the value in a variable ‘s‘.
  2. To convert seconds into hours, divide s by 3600. Store the results in variable ‘h‘. (h = s / 3600)
  3. Once we find the hours, now update the seconds variable by performing modulo operation. (s = s % 3600)
  4. To convert seconds into minutes, divide s by 60. Store the results in variable ‘m‘. (m = s / 60)
  5. Since, we have converted the seconds into hours and minutes. Finally, perform the modulo operation by 60 to update the seconds variable. (s = s % 60)

Flow Chart 🌻

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
  clrscr();
  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
  // Finally, update the variable "s"
  s = s % 60; // s = 63%60 = 3
  printf("\nHours: %d", h);
  printf("\nMinutes: %d", m);
  printf("\nSeconds: %d", s);
  getch();
}

Example 😍

Suppose user enters value of seconds represented by variable s as 3663.

We know that there are 3600 seconds in one hour. So, to find out the hours, we need to divide 3663 by 3600. After division, we get 1 as quotient and it will be stored in variable h which represents hours.

Once, we get the value of hours, we need to update the seconds variable s. Thus, we perform modulo operation by 3600 (i.e. 3663 % 3600) and in above example we get 63 as remainder.

Now, we have to find out the minutes, we know that there are 60 seconds in one minute. So, we divide seconds which is now 63 by 60 and we get 1 as quotient. This value is stored in variable m which represents minutes.

Again, we need to update the seconds variable s. So, we perform modulo operation by 60 (i.e. 63 % 60) and we get 3 as remainder.

Output:

Hours: 1
Minutes: 1
Seconds: 3

This is how we convert seconds into corresponding hours, minutes and seconds.
For more C programs, click here.

Categorized in: