Skip to content

Instantly share code, notes, and snippets.

@djsutherland
Created November 6, 2010 22:37
Show Gist options
  • Save djsutherland/665772 to your computer and use it in GitHub Desktop.
Save djsutherland/665772 to your computer and use it in GitHub Desktop.
CS 33: one solution to the time-difference problem
#include <stdio.h>
#include <stdlib.h>
// Prompts the user for two times (in hh:mm format) and outputs
// the difference between them, assuming they're on the same day.
// No error checking.
int main() {
int hours1, minutes1, hours2, minutes2;
int hourDiff, minuteDiff;
printf("Enter the first time: ");
scanf("%d:%d", &hours1, &minutes1);
printf("Enter the second time: ");
scanf("%d:%d", &hours2, &minutes2);
if (hours1 == hours2 && minutes1 == minutes2) {
printf("There is no difference between the times.\n");
return 0;
}
if (hours1 > hours2) {
hourDiff = hours1 - hours2;
minuteDiff = minutes1 - minutes2; // might be < 0, but right order
} else if (hours2 > hours1) {
hourDiff = hours2 - hours1;
minuteDiff = minutes2 - minutes1;
} else { // hours are equal
hourDiff = 0;
minuteDiff = abs(minutes2 - minutes1);
}
if (minuteDiff < 0) {
hourDiff--;
minuteDiff += 60;
}
printf("The difference between the times is");
if (hourDiff == 0)
;
else if (hourDiff == 1)
printf(" 1 hour");
else
printf(" %d hours", hourDiff);
if (hourDiff && minuteDiff)
printf(" and");
if (minuteDiff == 0)
printf(".\n");
else if (minuteDiff == 1)
printf(" 1 minute.\n");
else
printf(" %d minutes.\n", minuteDiff);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment