Write a C program to create a structure called date with day, month and year as the data member and to find the difference between two dates.
Special Constraints:
1. Get the start date and the end date.
2. Consider that both these days fall in the same year and that year will be a non-leap year.
3. Also, find the number of days between the given days.
4. Include both the starting date and ending date.
Sample Input and Output:
Enter the starting date
Enter the starting day
14
Enter the starting month
11
Enter the starting year
2015
Enter the ending date
Enter the ending day
17
Enter the ending month
11
Enter the ending year
2015
Number of days is 4
Implementation of the above problem:
#include<stdio.h>
// A date has day 'd', month 'm' and year 'y'
struct Date12
{
int d, m, y;
};
// To store number of days in all months from January to Dec.
const int monthDays[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// This function counts number of leap years before the given date
int countLeapYears(struct Date12 d)
{
int years = d.y;
// Check if the current year needs to be considered for the count of leap years or not
if (d.m <= 2)
years--;
// An year is a leap year if it is a multiple of 4, multiple of 400 and not a multiple of 100.
return years / 4 - years / 100 + years / 400;
}
// This function returns number of days between two given dates
int getDifference(struct Date12 dt1, struct Date12 dt2)
{
// COUNT TOTAL NUMBER OF DAYS BEFORE FIRST DATE 'dt1'
int i;
// initialize count using years and day
long int n1 = dt1.y*365 + dt1.d;
// Add days for months in given date
for ( i=0; i<dt1.m - 1; i++)
n1 += monthDays[i];
// Since every leap year is of 366 days, Add a day for every leap year
n1 += countLeapYears(dt1);
// SIMILARLY, COUNT TOTAL NUMBER OF DAYS BEFORE 'dt2'
long int n2 = dt2.y*365 + dt2.d;
for ( i=0; i<dt2.m - 1; i++)
n2 += monthDays[i];
n2 += countLeapYears(dt2);
// return difference between two counts
return (n2 - n1);
}
// Driver program
int main()
{
struct Date12 dt1;
struct Date12 dt2 ;
printf("Enter the starting date\n");
printf("Enter the starting day\n");
scanf("%d",&dt1.d);
printf("Enter the starting month\n");
scanf("%d",&dt1.m);
printf("Enter the starting year\n");
scanf("%d",&dt1.y);
printf("Enter the ending date\n");
printf("Enter the ending day\n");
scanf("%d",&dt2.d);
printf("Enter the ending month\n");
scanf("%d",&dt2.m);
printf("Enter the ending year\n");
scanf("%d",&dt2.y);
printf("Number of days is %d",getDifference(dt1,dt2)+1);
return 0;
}
Thanks
Mukesh Rajput
Post A Comment:
0 comments: