Unit Conversions Solution



#include <stdio.h>

main() {
  int seconds;
  int minutes;
  int hours;
  int days;

  printf("Enter the number of seconds: ");
  scanf("%d", &seconds);
  minutes = seconds / 60;
  hours = (seconds / 60) / 60;
  days = ((seconds / 60) / 60) / 24;
  printf("%d seconds = %d minute(s)\n", seconds, minutes);
  printf("%d seconds = %d hour(s)\n", seconds, hours);
  printf("%d seconds = %d day(s)\n", seconds, days);
}

Discussion


int seconds; Declares an integer variable seconds. In most systems the range will be between -2 billion and 2 billion.
int minutes; Declares an integer variable minutes.
int hours; Declares an integer variable hours.
int days; Declares an integer variable days.
printf("Enter the number of seconds: "); Print a message to the screen asking the user for an integer number of seconds.
scanf("%d", &seconds); The scanf function gets inputs from the standard input device and writes the values into the variables indicated. In this case, the %d specifies that an integer is to be read into the variable seconds. The ampersand (&) in front of the variable indicates that the address is passed into the scanf function so that the scanf function knows where to write the data to.
minutes = seconds / 60; Calculate the number of minutes with simple arithmetic. Note that any remainder is truncated.
hours = (seconds / 60) / 60; Calculate the number of hours with simple arithmetic. Note that any remainder is truncated.
days = ((seconds / 60) / 60) / 24; Calculate the number of days with simple arithmetic. Note that any remainder is truncated.
printf("%d seconds = %d minute(s)\n", seconds, minutes); Print the number of seconds and the converted number of minutes. The %d's are print masks for the two integers which are specified as the second and third parameters passed to the printf function.


Return to Homepage    Return to Programming Pages
Updated November 24, 2005. For comments and questions, send email to Vector.x64 @ gmail.com (without the spaces).