Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc).

Example of an expected output:

./last_sundays 2013
2013-01-27
2013-02-24
2013-03-31
2013-04-28
2013-05-26
2013-06-30
2013-07-28
2013-08-25
2013-09-29
2013-10-27
2013-11-24
2013-12-29


Related tasks
 Day of the week
 Five weekends
 Last Friday of each month


 
program Find_the_last_Sunday_of_each_month;
 
{$APPTYPE CONSOLE}
 
uses
  System.SysUtils,
  System.DateUtils;
 
// ADayOfWeek -> sunday is the first day and is 1
function LastDayOfWeekOfEachMonth(AYear, ADayOfWeek: Word): TArray<TDateTime>;
var
  month: word;
  daysOffset: Integer;
  date: TDatetime;
begin
  if (ADayOfWeek > 7) or (ADayOfWeek < 1) then
    raise Exception.CreateFmt('Error on FindAllDaysOfWeek: "%d" must be in [1..7] (sun..sat)',
      [ADayOfWeek]);
 
  SetLength(Result, 12);
 
  for month := 1 to 12 do
  begin
    date := EncodeDate(AYear, month, DaysInAMonth(AYear, month));
 
    daysOffset := DayOfWeek(date) - ADayOfWeek;
    if daysOffset < 0 then
      inc(daysOffset, 7);
 
    Result[month - 1] := date - daysOffset;
  end;
end;
 
var
  strYear: string;
  Year: Integer;
  date: TDateTime;
 
begin
  write('Year to calculate: ');
  Readln(strYear);
  if not TryStrToInt(strYear, Year) or (Year < 1900) then
    raise Exception.CreateFmt('Error: "%s" is not a valid year', [strYear]);
 
  for date in LastDayOfWeekOfEachMonth(Year, 1) do
    writeln(FormatDateTime('yyyy-mmm-dd', date));
 
  readln;
end.