I've been reading a lot about classes and object-oriented programming recently and I'm attempting to define a class called date with multiple member functions. One of my functions is called addDay() and I want it to be able to add a specified number of days to the current day, and be accurate throughout the months with different # of days.
So far, I feel like I am close, but I think I need to have the entire function in a loop in order for my "if else if" statements to be accurate. The problem is, I can't think of a good way to nest all of my if statements in a loop that breaks at the proper time. I'm a very amateur programmer trying my best to learn, so if there is a more efficient way of doing this and you would like to share, feel free as I will study it and be greatly appreciative. Thanks in advance!
Here is what I have so far: (day and month are private data members)
The addDay function I am trying to build came from an addMonth function I wrote that worked really well. I thought I could just modify it and make the necessary changes to challenge myself. Below is the addMonth function I wrote so you can see how I was thinking about the addDay function.
1 2 3 4 5 6 7 8 9 10
void addMonth(int n) {
int newMonth = month + n;
if (newMonth > 12) {
while (newMonth > 12)
newMonth -= 12;
month = newMonth;
}
else
month = n + month;
}
Why don't you use one simple array that holds the maximum numbers for every month, that way you can just do the same operation without having to to use a bunch of if/else's.
For example:
1 2 3 4 5 6 7 8
int month_max[12] = {31, 28,31,30,31, 30, 31,31, 30,31,30,31};
...
if (newDay > month_max[month-1]) // month-1 because arrays start at 0
{
// add one to month
}
Also, I don't understand why you're usig a while loop to reset days or months to zero, if you do
1 2
while (newMonth > 12)
newMonth -= 12;
It will normally always run only once, or if month is really high will give unexpected results.
If you're adding 3 months to december, the number will be 15, if you just add one year and then set month to 15-12, it will solve the problem much more easily, and just as important, make your code more readable to others as it's more clear what you're doing.
I figured there was a much more straight forward way of accomplishing this. Using an array is far more readable, not to mention much more efficient, than all of my if-else if statements with while loops. From now on, I will use arrays in similar situations.
I appreciate you're help and your valuable advice!