F
Felipe Ribeiro
I have to write a program that asks the user to enter a number of
dates and then determines which one is the earliest.
I solved the problem but I think there might be a better way to do it.
Here's the code I wrote:
-------------------------------------------------------------------------------------------------------------
#include <stdio.h>
int main(void)
{
int day, month, year, date;
/*
* Initially earliest needs to be greater than any date, so
initialize
* it with a large value
*/
int earliest = 10000000;
for (; {
printf("Enter a date (mm/dd/yy): ");
scanf("%d / %d / %d", &month, &day, &year);
if (month == 0 && day == 0 && year == 0)
break;
/* Put the date into a number, so it's easier to operate on it */
date = year * 10000 + month * 100 + day;
if (date < earliest)
earliest = date;
}
printf("The earliest date is %.2d/%.2d/%.2d\n",
(earliest - ((earliest / 10000) * 10000)) / 100, earliest % 100,
earliest / 10000);
return 0;
}
-------------------------------------------------------------------------------------------------------------
I'd like to know if I could make any changes to improve the program.
Make it clearer or more elegant... I don't know.
For example, if I wrote
printf("Enter a date (mm/dd/yy): ");
scanf("%d / %d / %d", &month, &day, &year);
while (month == 0 && day == 0 && year == 0) {
printf("Enter a date (mm/dd/yy): ");
scanf("%d / %d / %d", &month, &day, &year);
....
code
...
}
would it be better than using an infinite loop? Would it improve
anything on performance?
dates and then determines which one is the earliest.
I solved the problem but I think there might be a better way to do it.
Here's the code I wrote:
-------------------------------------------------------------------------------------------------------------
#include <stdio.h>
int main(void)
{
int day, month, year, date;
/*
* Initially earliest needs to be greater than any date, so
initialize
* it with a large value
*/
int earliest = 10000000;
for (; {
printf("Enter a date (mm/dd/yy): ");
scanf("%d / %d / %d", &month, &day, &year);
if (month == 0 && day == 0 && year == 0)
break;
/* Put the date into a number, so it's easier to operate on it */
date = year * 10000 + month * 100 + day;
if (date < earliest)
earliest = date;
}
printf("The earliest date is %.2d/%.2d/%.2d\n",
(earliest - ((earliest / 10000) * 10000)) / 100, earliest % 100,
earliest / 10000);
return 0;
}
-------------------------------------------------------------------------------------------------------------
I'd like to know if I could make any changes to improve the program.
Make it clearer or more elegant... I don't know.
For example, if I wrote
printf("Enter a date (mm/dd/yy): ");
scanf("%d / %d / %d", &month, &day, &year);
while (month == 0 && day == 0 && year == 0) {
printf("Enter a date (mm/dd/yy): ");
scanf("%d / %d / %d", &month, &day, &year);
....
code
...
}
would it be better than using an infinite loop? Would it improve
anything on performance?