import java.util.Scanner;
public class DayToDate
{
static String months[] = {"JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY",
"AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER"};
static boolean isLeap(int y)
{
return (y % 400 == 0) || (y % 100 != 0 && y % 4 == 0);
}
static String suffix(int d)
{
if (d >= 11 && d <= 13)
return "TH.";
switch (d % 10)
{
case 1: return "ST.";
case 2: return "ND.";
case 3: return "RD.";
default: return "TH.";
}
}
// converts a day number of a year to a date; rolls over into the next year if needed
static String toDate(int dn, int y)
{
while (dn > (isLeap(y) ? 366 : 365))
{
dn = dn - (isLeap(y) ? 366 : 365);
y++;
}
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeap(y))
days[1] = 29;
int m = 0;
while (dn > days[m])
{
dn = dn - days[m];
m++;
}
return dn + suffix(dn) + " " + months[m] + " " + y;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("DAY NUMBER : ");
int dn = sc.nextInt();
System.out.print("YEAR : ");
int y = sc.nextInt();
System.out.print("DATE AFTER : ");
int n = sc.nextInt();
int maxDays = isLeap(y) ? 366 : 365;
if (y < 1000 || y > 9999 || dn < 1 || dn > maxDays || n < 1 || n > 100)
{
System.out.println("INVALID INPUT");
return;
}
System.out.println();
System.out.println(toDate(dn, y));
System.out.println("DATE AFTER " + n + " DAYS :");
System.out.println(toDate(dn + n, y));
}
}
Explanation: isLeap() tells whether the year is a leap year (divisible by 400, or by 4 but not by 100), which decides whether February has 28 or 29 days and whether the year has 366 or 365 days. toDate(dn, y) first moves into the next year while the day number is larger than the number of days in the year (needed for the date after N days), then subtracts the days of each month one by one until the remaining number fits in a month; that remainder is the date. suffix() adds ST., ND., RD. or TH. (TH. for 11, 12 and 13). main() accepts the day number (1 to 366), the 4-digit year and N (1 to 100), rejects invalid values, and prints the date for the day number and the date after N more days. Tested with both samples: 233, 2020, 17 gives 20TH. AUGUST 2020 and 6TH. SEPTEMBER 2020; 360, 2020, 45 gives 25TH. DECEMBER 2020 and 8TH. FEBRUARY 2021.