Date Class: Using a class

In about 1790 Carl Friedrich Gauss, a German mathematician developed an algorithm for calculating the day of the week for January 1 of any year. Others have added to it to calculate the day of the week for any date.

The weekday function returns 0 for Sunday, 1 for Monday, etc. Printing the value returned by the weekday method would be meaningless. Instead we use an array the names of the days.

You may wonder why not just return a string with the name of the day? Returning an integer make the class much more versatile. We might want to do something else with it, or print it in another language.

1
2
3
4
5
6
7
8
9
10
11
#include "c:/cpp/classes/Date.cpp"
#include <iostream>
using namespace std;
int main() {
   string dayNames[7]={"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
   Date today;
   int weekday=today.weekday();
   cout<<"Today is "<<dayNames[weekday]<<endl;
   system("pause");
   return 0;
}
CODE

Challenge

Use the getMonth, getDay and getYear methods and print the date as Thursday, October 19, 2017

NEXT: Classes: Creating classes