Exercise 1-13 - CBD p. 38

Solution index                   Textual C program


#include <stdio.h>


int main(void) {  
  
  int inputValue, rest_seconds, hours, minutes, seconds;
  int status = 0;

  printf("Input the number of seconds: ");
  scanf("%d", &inputValue);

  hours = inputValue / 3600;
  rest_seconds = inputValue % 3600;
  minutes = rest_seconds / 60;
  seconds = rest_seconds % 60;

  printf("\n%d seconds correspond to %d hours, %d minutes, and %d seconds.\n", 
	 inputValue, hours, minutes, seconds);
 
  return status;    

}
 

  int inputValue, rest_seconds, hours, minutes, seconds;
  int status = 0;
Six integer variables are declared, one is also initialized.
 

  printf("Input the number of seconds: ");
  scanf("%d", &inputValue);
The user is asked to enter the number of seconds. The value entered is placed in the inputValue variable. As of now, you should just accept that the call of scanf is the way to read an integer value. Later in the course we will come back to the details.
 

  hours = inputValue / 3600;
  rest_seconds = inputValue % 3600;
  minutes = rest_seconds / 60;
  seconds = rest_seconds % 60;
This is where the calculation takes place. We first obtain the number of hours by dividing by (60*60 = 3600). The number of seconds left is then assigned to rest_seconds. Notice that the number of seconds left is in between 0 and 3599. Then the number of minutes is obtained by dividing rest_seconds seconds by 60, and finally the number of seconds left is obtained by calculating the remainder in an integer division by 60. This is an integer number between 0 and 59. Be sure that you understand the algorithmic aspects of these calculations!
 

  printf("\n%d seconds correspond to %d hours, %d minutes, and %d seconds.\n", 
	 inputValue, hours, minutes, seconds);
The result is printed out. For each occurrence of %d, the value of the corresponding integer variable in the sequence following the string is inserted at that place in the string.
 

  return status;    
Terminate program.
 


Generated: Wednesday, March 29, 2006, 12:33:01
This program dissection page is generated from an XML-in-LAML source file