Please reply with text answer directly on Chegg. Please do not post a picture of
ID: 3782332 • Letter: P
Question
Please reply with text answer directly on Chegg. Please do not post a picture of answer,
Thanks
Write a program that asks the user for a date in the format mm/dd/yyyy, using a custom struct to store the date information entered in memory. The program should call a custom function that adds seven days to the user's date, passing in the data in and out of the custom function using the custom struct for the dates. The program should then print out the original date entered and the date one week later. C code should include meaningful comments to explain what the code does and how it works.
Explanation / Answer
Solution:
#include <stdio.h>
struct date {
int month;
int day;
int year;
};
// function adds 7 days to the date
struct date addSevenDays(struct date newDate)
{
// add 7 days
newDate.day += 7;
// months having 31 days
if ((newDate.month == 1 || newDate.month == 3 || newDate.month == 5 || newDate.month == 7 ||
newDate.month == 8 || newDate.month == 10 || newDate.month == 12) && newDate.day > 31)
{
// new month
newDate.day -= 31;
newDate.month += 1;
}
// months having 30 days
else if ((newDate.month == 4 || newDate.month == 6 || newDate.month == 9 || newDate.month == 11) && newDate.day > 30)
{
newDate.day -= 30;
// new month
newDate.month += 1;
}
// February
else
{
if (newDate.year % 4 == 0 && newDate.day > 29)
{
newDate.day -= 29;
newDate.month += 1;
}
else if (newDate.day > 28)
{
newDate.day -= 28;
newDate.month += 1;
}
}
// year changed
if (newDate.month > 12)
{
newDate.month = 1;
newDate.year += 1;
}
return newDate;
}
int main() {
struct date originalDate;
struct date newDate;
// prompt to read the date
printf("Enter a date in mm/dd/yyyy format: ");
scanf("%d/%d/%d", &originalDate.month, &originalDate.day, &originalDate.year);
// call function to add 7 days and assign it to newDate
newDate = addSevenDays(originalDate);
printf(" Original Date: %d/%d/%d ", originalDate.month, originalDate.day, originalDate.year);
printf(" New Date after adding 7 days: %d/%d/%d ", newDate.month, newDate.day, newDate.year);
return 0;
}
Output:
Enter a date in mm/dd/yyyy format: 1/21/2017
Original Date: 1/21/2017
New Date after adding 7 days: 1/28/2017
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.