Exercise 5 draft

Added Exercise 5 but incomplete
This commit is contained in:
2025-03-21 23:35:38 +01:00
parent d1c3fcd614
commit 4655cd3477
4 changed files with 226 additions and 0 deletions

View File

@@ -0,0 +1,90 @@
#include "calendar.h"
#include <string>
// PRE: a year greater or equal than 1900
// POST: returns whether that year was a leap year
bool is_leap_year(int year) {
if (year >= 1900) {
if (year % 4 == 0 && year % 100 != 0)
return true;
else if (year % 4 == 0 && year % 400 == 0)
return true;
}
return false;
}
// PRE: a year greater or equal than 1900
// POST: returns the number of days in that year
int count_days_in_year(int year) {
if (year >= 1900) {
if (is_leap_year(year) == true)
return 366;
return 365;
}
return 0;
}
// PRE: a month between 1 and 12 and a year greater or equal than 1900
// POST: returns the number of days in the month of that year
int count_days_in_month(int month, int year) {
if (year >= 1900 && month > 0 && month <= 12) {
if (is_leap_year(year) == false) {
if (month % 2 != 0 && month != 2 && month <= 7)
return 31;
else if (month % 2 == 0 && month != 2 && month > 7)
return 31;
else if (month == 2)
return 28;
else
return 30;
} else {
if (month % 2 == 0 && month != 2 && month <= 7)
return 31;
else if (month % 2 == 0 && month != 2 && month > 7)
return 31;
else if (month == 2)
return 29;
else
return 30;
}
}
return 0;
}
// PRE: n/a
// POST: returns whether the given values represent a valid date
bool is_valid_date(int day, int month, int year) {
if (day > 0 && day <= count_days_in_month(month, year) && month > 0 &&
month <= 12 && year >= 1900)
return true;
return false;
}
// PRE: the given values represent a valid date
// POST: returns the number of days between January 1, 1900 and this date
// (excluding this date)
int count_days(int day, int month, int year) {
int res_day = 0;
if (is_valid_date(day, month, year) == true) {
for (int j = 1901; j <= year; ++j) {
res_day += count_days_in_year(j);
}
for (int j = 1; j < month; ++j) {
res_day += count_days_in_month(j, year);
}
res_day += (day - 1);
}
return res_day;
}
// PRE: the given values represent a (potentially invalid) date
// POST: prints the weekday if the date is valid or "invalid date" otherwise.
// Everything must be printed in lowercase.
void print_weekday(int day, int month, int year) {
if (is_valid_date(day, month, year) == true) {
std::string days[7] = {"sunday", "monday", "tuesday", "wednesday",
"thursday", "friday", "saturday"};
std::cout << days[((count_days(day, month, year) + 1) % 7)];
} else
std::cout << "invalid date";
}