Exercise: Number of Days Between Two Dates
Let's combine our newly obtained scanf
power with the power of conditions and loops, and write something that will probably be more serious program than anything before! It might take longer time than all previous exercises. We are getting real! As always, if you are stuck, please don't hesitate to contact me and ask your questions.
You will calculate number of days between two dates. Computers are fast, so the easiest way of doing it is to iterate from the first date to the second date, incrementing one day at a time, and counting how many iterations you did.
You can have six variables:
int year1, month1, day1;
int year2, month2, day2;
Read them using scanf
and keep incrementing a date until you reach another date.
Two things to keep in mind:
Leap years
Some years are leap years: they have 29 days in February. A year is a leap year if it is divisible by 400, or divisible by 4 but not by 100. In C, that would translate to the following function, feel free to copy it to your code. Years 1896, 1904, 1996, 2000, and 2004 were leap years, but year 1900 was not.
int is_leap_year(int y) {
return y % 400 == 0 || (y % 4 == 0 && y % 100 != 0);
}
Number of days in a month
You will need to know how many days are in the current month. We haven't talked about arrays and about switch
statement yet, so your only option at this moment is to have a set of conditions. You can just write a simple function:
int number_of_days(int y, int m) {
if (m == 1) return 31;
if (m == 2) {
if (is_leap_year(y)) return 29;
return 28;
}
if (m == 3) return 31;
...
}
Note how I'm omitting { }
braces in this case; I feel it's acceptable in very straightforward functions like this one. Also note that since each return
exits the function, there's no need to use else
.
Okay, now you are ready to put all these puzzle pieces together! The answer for the given example is 2, we don't count the last day of the range.
#include <stdio.h>
int main() {
int result = 0;
/* your code here. a lot of code! */
printf("%d\n", result);
return 0;
}
There are some unexpected tests! Make sure that all of them pass. If your code does something you cannot understand, add some printf
statements here and there to debug.
If it worked–good job!