hours

We use pointers in this program to pass integer variables to a function by reference, meaning we pass their addresses. The function stores the number of hours and minutes in the variables whose addresses are stored in the parameters.

This allows the function to " return" more than one piece of information to its caller.

The Program

/********************************************** * File: hours.c * Author: Sue Bogar * Date: 8/25/99 * Section: 101 * EMail: bogar@cs.umbc.edu * * This program converts a time given in minutes * into separate values representing hours and * minutes. The program is written as an * illustration of C's mechanism known as * call by reference. **********************************************/ #include <stdio.h> #define MINUTES 60 /* Function prototypes */ void ConvertTimeToHM (int time, int *pHours, int *pMinutes); int main() { int time, hours, minutes; printf("Test program to convert time values\n"); printf("Enter a time duration in minutes: "); scanf ("%d", &time); ConvertTimeToHM (time, &hours, &minutes); printf("HH:MM format: %d:%02d\n", hours, minutes); return 0; } /********************************************** * Function: ConvertTimeToHM * Usage: ConvertTimeToHM (time, &hours, &minutes); * Inputs: the current time as integer minutes * a pointer to an int variable to hold the * hours a pointer to an int variable to * hold the minutes * Output: the hours and minutes are stored in their * respective variables * there is no return value * NOTES: * This function converts a time value given in * minutes into an integral number of hours and * the remaining number of minutes. Note that the * last two arguments must be passed using their * addresses so that the function can correctly * set those values. **********************************************/ void ConvertTimeToHM (int time, int *pHours, int *pMinutes) { *pHours = time / MINUTES; *pMinutes = time % MINUTES; }

The Sample Run

linux1[83] % gcc -Wall -ansi hours.c linux1[84] % a.out Test program to convert time values Enter a time duration in minutes: 30 HH:MM format: 0:30 linux1[85] % !a a.out Test program to convert time values Enter a time duration in minutes: 70 HH:MM format: 1:10 linux1[86] % !a a.out Test program to convert time values Enter a time duration in minutes: 757 HH:MM format: 12:37 linux1[87] %
Last Modified -