I was making this small exercise in wich I have to enter a certain date meaning, day, month and year.
If entered it should count the amount of days from the beginning of that year and print it.

I found a solution for this, but was wondering wether there is an alternative or maybe somethings you might change in this code. I know that there is a certain library wich makes this automatically, but then again, it wouldn't be much of an exercise now would it ;)

The code is:

``````int main()
{
int dag, maand;
int month= 1, year=0, amount=0;

cin>> dag;cin.get();
cin>> maand;cin.get();
cin>> year;cin.get();

int tabel[12]={31,28,31,30,31,30,31,31,30,31,30,31};
tabel[1]=28+(year%4==0 && year%100 !=0 || year %400==0);

for (int i=0;i<maand;i++)
{
if(month!=maand)
{
amount+=tabel[i];
month++;
}
}
for (int day=0; day<dag; day++)
{
{
amount++;
}
}

cout<<amount<<endl;

return 0;
}``````

## All 3 Replies

There's nothing wrong with your code aside from formatting and redundant braces. Though the last loop could simply be an assignment because all you're doing is adding dag to amount. Here's how my first attempt would do it:

``````#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
const int days_in_month[][12] = {
{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
};
int day, month, year;
int total = 0;

cout<<"Enter date (yyyy mm dd): ";
if (!(cin>> year >> month >> day))
return EXIT_FAILURE;

const int leap = (year % 4 == 0 && year % 100 !=0 || year % 400 == 0);

for (int i = 0; i < month - 1; i++)
total += days_in_month[leap][i];
total += day;

cout<< total <<endl;

return EXIT_SUCCESS;
}``````

>tabel[1]=28+(year%4==0 && year%100 !=0 || year %400==0);
This is clever, and I can't really say anything bad about the practice other than it's not always the best idea to modify something that would be more suited as a constant value. That's just my opinion though.

Thanks Narue,

Changed the last loop and deleted those braces, like you said, there not needed !