I would love to know your opinion about this algorithm that we wrote in class. I was thinking about how I can optimize it (in terms of size of code/complexity) without using library functions (besides <iostream>
for reading and writing).
Assignment (translated):
Gregorian calendar rule about leap years was introduced on (Friday) 15 of October in 1582. Write a program that when given a date in format “dd.MM.yyyy", will display the name of that day. You need to define and use enum type
Weekday
{Monday, Tuesday, …, Sunday}.
Here is my code:
#include <iostream>
bool isLeapYear(int year){
if(year % 4 == 0 && year % 100 != 0){
return true;
} else if (year % 400 == 0){
return true;
} else {
return false;
}
}
enum Weeknday {Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday};
int main() {
// Get date
int day,mounth,year;
scanf("%d.%d.%d",&day,&mounth,&year);
// Count days
int days = 0;
for(int i = 1582; i <= year; i++){
if(i != year) {
if(isLeapYear(i)){
days += 366;
} else {
days += 365;
}
} else {
for(int j = 1; j <= mounth; j++){
if(j != mounth){
if(j == 1 || j == 3 || j == 5 || j == 7 || j == 8 || j == 10 || j == 12){
days += 31;
} else if (j == 4 || j == 6 || j == 9 || j == 11){
days += 30;
} else if (j == 2){
if(isLeapYear(i)){
days += 29;
} else {
days += 28;
}
}
} else {
days += day;
}
}
}
}
int a = (days-3)%7;
Weeknday enum_day;
switch(a) {
case 1:
enum_day = Monday;
std::cout << "Monday";
break;
case 2:
enum_day = Tuesday;
std::cout << "Tuesday";
break;
case 3:
enum_day = Wednesday;
std::cout << "Wednesday";
break;
case 4:
enum_day = Thursday;
std::cout << "Thursday";
break;
case 5:
enum_day = Friday;
std::cout << "Friday";
break;
case 6:
enum_day = Saturday;
std::cout << "Saturday";
break;
case 7:
enum_day = Sunday;
std::cout << "Sunday";
break;
}
std::cout << enum_day;
}
Tuesday
instead ofMonday
. We can't review code that isn't working correctly. Fix the bug first. We only review code that is working as expected, there are other sites that will help you debug your code. Please read Where can I get help? and How do I ask a good question?. \$\endgroup\$