The program prints previous date of the entered input. It validates leap year, month and date to check whether the given date is valid or not. We have simply used nested if in the logic to achieve the functionality.
C Program to determine the previous date
Program:
#include<conio.h> #include<stdio.h> int main () { int month, date, year, valid = -1, leap_year = -1, invalid_input = -1; printf ("please enter a date = "); scanf ("%d", &date); printf ("please enter a month = "); scanf ("%d", &month); printf ("please enter a year = "); scanf ("%d", &year); if ((date > 0 && date <= 31) && (month >= 1 && month <= 12) && (year >= 2000 && year <= 2050)) { invalid_input = 1; // finding given input is a leap year or not if ((year % 4) == 0) { leap_year = 1; if ((year % 100) == 0) { if ((year % 400) == 0) { leap_year = 1; } else { leap_year = -1; } } } if (month == 2 && leap_year == 1 && date > 29) valid = -1; else if (month == 2 && leap_year == -1 && date > 28) valid = -1; else valid = 1; } if ((month == 6 || month == 4 || month == 9 || month == 11) && date > 30) valid = -1; // validating & finding output if (valid == 1) { printf ("Entered date = %d-%d-%d", date, month, year); if (date == 1) { if (month == 1) { date = 31; month = 12; year--; } else if (leap_year = 1 && month == 3) { date = 29; month--; } else if (leap_year == -1 && month == 3) { date = 28; month--; } else if (month == 2 || month == 4 || month == 6 || month == 8 || month == 9 || month == 11) { date = 31; month--; } else { date = 30; month--; } } else { date--; } printf ("\nPrevious date = %d-%d-%d \n", date, month, year); } if (valid == -1 && invalid_input == 1) printf ("\n Not a valid date"); if (invalid_input == -1) printf ("\n Invalid Input"); return 0; }
Output:
Testing the program:
Invalid Date:
please enter a date = 31 please enter a month = 6 please enter a year = 2030 Not a valid date
Previous Date:
please enter a date = 21 please enter a month = 6 please enter a year = 2030 Entered date = 21-6-2030 Previous date = 20-6-2030