My First Program

I've made a ton of really small, one file programs that do nothing more than help me learn what I'm working on. This was my first big project as a programmer and I thought I would submit it for review from the forums.

I feel like this could have been simpler with a class, but wasn't completely sure how to set it up (if anyone wants to let me know.) I am also not 100% sure that the math is perfect, and it may be a little off. The only thing that seems definitely off is the hours, but I'm really not sure how to fix it.

This program will ask for your birthday and output how old you are in years, days, hours, minutes and seconds. Constructive criticism is very welcome! I've only been coding roughly 1-2 months, so keep that in mind. :D

Functions.h
1
2
3
4
5
6
7
8
9
#include <iostream>
#include <Windows.h>
#define DEBUGFUNCTIONS_CODE
#define DEBUGMAIN_CODE

void DaysLeftInYear(int, int, int, int &);
void TimePassed(int , int , int, int, int, int, int, int &, int &, int &, int &, int &, int);
void PrintAge(int, int, int, int, int, int, int, int, int, int, int);
int OurMenu();


Functions.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include "Functions.h"
using namespace std;

void TimePassed(int birthYear, int curYear, int monthBorn, int curMonth, int dayBorn, int curDay, int daysPassedBor, 
	int &daysPassed, int &yearsPassed, int &hoursPassed, int &minutesPassed, int &secondsPassed, int daysPassedCur)
{
	daysPassed = 0;

	//Loop to add how many days have passed each year
	for(int i = birthYear; i < curYear; i++)
	{
		//Check for leap year
		if (i % 400 == 0 || (i % 100 != 0 && i % 4 == 0) )
		{
			daysPassed += 366;
		} else { daysPassed += 365; }
	}

	//Fix days
	int dayFix = daysPassedCur - daysPassedBor;
	daysPassed += dayFix;

	//Calculate years, hours, minutes and seconds have passed
	//up to the current year
	yearsPassed = daysPassed / 365;
	hoursPassed = daysPassed * 24;
	minutesPassed = hoursPassed * 60;
	secondsPassed = minutesPassed * 60;

	


#ifdef DEBUGFUNCTIONS_CODE
	cout << "      -DEBUG-      " << endl;
	cout << "TimePassed() Values" << endl;
	cout << "-------------------" << endl;
	cout << yearsPassed << " years have passed. Variable: yearsPassed" << endl;
	cout << daysPassed << " days have passed. Variable: daysPassed" << endl;
	cout << hoursPassed << " hours have passed. Variable: hoursPassed" << endl;
	cout << minutesPassed << " minutes have passed. Variable: minutesPassed" << endl;
	cout << secondsPassed << " seconds have passed. Variable: secondsPassed" << endl << endl;
#endif
}

void DaysLeftInYear(int year, int month, int day, int &daysPassed)
{
	int daysLeft = 0;
	int daysInMonth = 0;
	bool leapYear = false;

	//Check for leap year
	if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0) )
	{			
		leapYear = true;
	} else { 
		leapYear = false; 
	}

	switch(month)
	{
	case 1:
		daysInMonth = 31;
		daysLeft += daysInMonth;
	case 2:
		//Check for leap year
		if (leapYear == true)
		{
			daysInMonth = 29;
		} else { 
			daysInMonth = 28; 
		}
		daysLeft += daysInMonth;
	case 3:
		daysInMonth = 31;
		daysLeft += daysInMonth;
	case 4:
		daysInMonth = 30;
		daysLeft += daysInMonth;
		
	case 5:
		daysInMonth = 31;
		daysLeft += daysInMonth;
	case 6:
		daysInMonth = 30;
		daysLeft += daysInMonth;
	case 7:
		daysInMonth = 31;
		daysLeft += daysInMonth;
	case 8:
		daysInMonth = 31;
		daysLeft += daysInMonth;
	case 9:
		daysInMonth = 30;
		daysLeft += daysInMonth;
	case 10:
		daysInMonth = 31;
		daysLeft += daysInMonth;
	case 11:
		daysInMonth = 30;
		daysLeft += daysInMonth;
	case 12:
		daysInMonth = 31;
		daysLeft += daysInMonth;
	default:
		cout << "Calculating..." << endl;
	}

	if (leapYear == true)
	{
		daysPassed = (366 - daysLeft + day) - 1;
	} else { 
		daysPassed = (365 - daysLeft + day) - 1;
	}

#ifdef DEBUGFUNCTIONS_CODE
	cout << "      -DEBUG-      " << endl;
	cout << "DaysLeftInYear() Values" << endl;
	cout << "-------------------" << endl;
	cout << daysLeft << " days left in the year. Variables: daysLeft" << endl;
	cout << daysPassed << " days passed already. Variable: daysPassed" << endl;
#endif
}


Main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include "Functions.h"
using namespace std;

int main()
{
	//Find current date
	SYSTEMTIME systime;
	GetSystemTime(&systime);
	int curYear = systime.wYear;
	int curMonth = systime.wMonth;
	int curDay = systime.wDay;
	int curHour = systime.wHour;
	int curMinute = systime.wMinute;
	int curSecond = systime.wSecond;

	//Setup birthday variables
	int monthBorn, dayBorn, yearBorn;

	cout << "What month were you born (1-12): ";
	cin >> monthBorn;

	cout << "What day were you born (1-31): ";
	cin >> dayBorn;

	cout << "What year were you born: ";
	cin >> yearBorn;

	//Initialize all DaysLeftInYear() variables
	int daysPassedCur = 0;
	int daysPassedBor = 0;

	//Calculate how much time has passed in the CURRENT year
	DaysLeftInYear(curYear, curMonth, curDay, daysPassedCur);
	DaysLeftInYear(yearBorn, monthBorn, dayBorn, daysPassedBor);

	//Initialize all TimePassed() variables
	int daysPassed = 0;
	int yearsPassed = 0;
	int hoursPassed = 0;
	int minutesPassed = 0;
	int secondsPassed = 0;

	//Calculate how much time has passed DISREGARDING the current year
	TimePassed(yearBorn, curYear, monthBorn, curMonth, dayBorn, curDay, daysPassedBor,  
		daysPassed, yearsPassed, hoursPassed, minutesPassed, secondsPassed, daysPassedCur);

#ifdef DEBUGMAIN_CODE
	cout << "      -DEBUG-      " << endl;
	cout << "main() Values" << endl;
	cout << "-------------------" << endl;
	cout << "curYear: " << curYear << endl;
	cout << "curMonth: " << curMonth << endl;
	cout << "curDay: " << curDay << endl;
	cout << "curSecond: " << curSecond << endl;
	cout << "monthBorn: " << monthBorn << endl;
	cout << "yearBorn: " << yearBorn << endl;
	cout << "dayBorn: " << dayBorn << endl;
	cout << "daysPassedCur: " << daysPassedCur << endl;
	cout << "daysPassedBor: " << daysPassedBor << endl;
	cout << "daysPassed: " << daysPassed << endl;
	cout << "yearsPassed: " << yearsPassed << endl;
	cout << "hoursPassed: " << hoursPassed << endl;
	cout << "minutesPassed: " << minutesPassed << endl;
	cout << "secondsPassed: " << secondsPassed << endl;
#endif

	int theChoice = OurMenu();
	PrintAge(theChoice, yearsPassed, daysPassed, daysPassedBor - daysPassedCur, hoursPassed, curHour, 
		minutesPassed, curMinute, secondsPassed, curSecond, curYear);

	return 0;

}

void PrintAge(int choice, int totalYears, int totalDays, int daysSinceYear, int totalHours, int hoursSinceDay, 
			  int totalMinutes, int minutesSinceHour, int totalSeconds, int secondsSinceHour, int curYear)
{
	enum Choice { YEARS = 1, DAYS, HOURS, MINUTES, SECONDS };
	
	
		if (daysSinceYear >= 365)
		{
			daysSinceYear %= 365;
			totalYears++;
		}
		

	switch(choice)
	{
	case YEARS:
		cout << "You are " << totalYears << " years, " << daysSinceYear << " days, "
			<< hoursSinceDay << " hours, " << minutesSinceHour << " minutes, and " 
			<< secondsSinceHour << " seconds old." << endl;
		break;
	case DAYS:
		cout << "You are " << totalDays << " days, " << hoursSinceDay << " hours, "
			<< minutesSinceHour << " minutes, and " << secondsSinceHour
			<< " seconds old." << endl;
		break;
	case HOURS:
		cout << "You are " << totalHours << " hours, " << minutesSinceHour << 
			" minutes, and " << secondsSinceHour << " seconds old." << endl;
		break;
	case MINUTES:
		cout << "You are " << totalMinutes << " minutes and " << secondsSinceHour 
			<< " seconds old." << endl;
		break;
	case SECONDS:
		cout << "You are " << totalSeconds << " seconds old." << endl;
		break;
	default:
		cout << "ERROR!" << endl;
		break;
	}

}

int OurMenu()
{
	int myChoice = 0;

	cout << "----------Birthday Menu----------" << endl;
	cout << "[1] Regular output" << endl;
	cout << "[2] Total days" << endl;
	cout << "[3] Total hours" << endl;
	cout << "[4] Total Minutes" << endl;
	cout << "[5] Total Seconds" << endl;

	cin >> myChoice;

	return(myChoice);
}
Last edited on
NOTE:
Line 19 of Functions.cpp is wrong, I messed up on the math. I'll work on fixing it a little bit later.

EDIT:
I added and commented a temporary fix until I sit down and sort through it. I've been working on this code (mostly the math) for about 2 hours so I'm going to take a break for a little while.

EDIT2:
Should be fully fixed and working 100%!! Please leave comments, I really would like to improve my coding and if there's anything that was sloppy I want to make sure it's fixed before I move on.
Last edited on
Very nice. Next use a library:
http://en.wikipedia.org/wiki/Time_t

:P

It is important to practice coding but the most important thing you should know, in programming, if you don't already.

"Don't reinvent the wheel, just realign it."
-Anthony J. D'Angelo

I used the <Windows.h> library to get the current date in Main.cpp
1
2
3
4
5
6
7
8
9
	//Find current date
	SYSTEMTIME systime;
	GetSystemTime(&systime);
	int curYear = systime.wYear;
	int curMonth = systime.wMonth;
	int curDay = systime.wDay;
	int curHour = systime.wHour;
	int curMinute = systime.wMinute;
	int curSecond = systime.wSecond;
Yeah but with time_t you can extract the time difference between the birthdate and current date. Then you can use that to work out seconds, minutes, hours, days etc.
That is true but because time_t only goes back as far as 1970 from my understanding, I chose to use a different method.
Those people born before then don't count. :P
Could anyone with some experience possibly add my project to your compiler and see if you can play around with it for some optimization. The only "issue" is the hours that have passed in the current day seem to be off for some reason, but what I'm more interested in than the math is how to optimize the code.

I am also very interested in how I could have used a class to make this code simpler and easier to understand. I thought about making a class and then calling my functions with a reference to the class instead of having something like 10 parameters. I'm just not really sure how I could do this the best (and correct) way.

So please, if any more experienced programmers have some time then please help me. I would like some tips on how to optimize it and how I could have better programmed it, including how I could have used a class instead (and if this would have been a much better method.) Also any comments on how well you think I did given my 1-2 months experience.
Why don't you first come out with your class implementation to encapsulate those functionalities and then other ppl can comment on it ? It is easier that way.
I think it is a bit too late for that tonight (12 AM where I live.) I have written a basic outline of how I will design my class for tomorrow.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Birthday
{
private:
	int totalYears;
	int totalMonths;
	int totalWeeks;
	int totalDays;
	int totalHours;
	int totalSeconds;
public:
	Birthday(int birthYear, int birthMonth, int birthDay);
	~Birthday();
	void GetBirthTotal();
	void PrintBirthTotal();
};


Basically I think I will have my class hold ALL of the variables that will be needed for this program. Then I will implement these functions with the class constructer and print the final numbers with different class functions.

I haven't fully learned, or attempted, to pass a class into a non-class function yet so I won't do that. I also think this method would be simpler and more effective than passing the class into a non-class function. What do you think?

PS: Sorry if I don't answer right away, I am going to sleep soon.
1
2
3
4
5
6
7
8
9

class Birthday {

...

friend operator<<(ostream&, const Birthday&); 

};


For all C++ classes I create I like to have the above handy function so I can print all the class internals in the most intuitive manner. More for trouble-shooting purposes.

Have a good sleep.
So please, if any more experienced programmers have some time


Are you trying to say something? I understand you want to improve your existing code by tweaking it but the advice I gave you is very good advice. I wouldn't easily disregard it.

Time_t may not necessarily be the library you are looking for but there are plenty out there and re-using existing code is what separates average programmers from great ones.
Last edited on
Well the whole point of this project was for me to use what I've learned so far to create a decent sized and fairly functional program. So if I used some library that did EVERYTHING, that would completely get rid of the point. I'm also not really sure what you mean by use a library..
 
int TotalDays = LibraryTotalDays(birthYear, birthMonth, birthDay);

Are you talking about something like that? Because as far as I know, other than time, no libraries that come with Visual Studio do anything like that. I actually did Google for some C++ source code that did something similar to what I was trying to do... But found absolutely nothing useful, so I ended up coding it 100% on my own with no help.

Again though, if I had a program that included some 3rd party library and did my entire program in 3 lines then it would defeat the purpose. I wrote this to learn and practice C++, not how to implement other peoples libraries. Do you even know of a library that would do this? Because I checked Google for calculating time between dates and found hardly anything worthwhile.
Last edited on
I didn't say that it was wrong to do this. Its great that you are practicing coding. I was just trying to help you by giving you solid advice. And asked you to extend your program by using a library such as <time.h>. This advice is what separates novice programmers from great programmers in the software industry.

Remember you will still be practicing coding if you use a library or not. Except if you reuse existing code it will save you time so you can write 2 or 3 programs in the time that it would take you to write 1 if you had to start from scratch.

Btw this took me 15 minutes to prove my point:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <stdio.h>
#include <time.h>
 
int main(void)
{
    // Times
    time_t rawtime;
    time_t birthtime;
    time_t now = time(NULL);

    // Difference from birthdate and current date in seconds
    double diffSeconds;
    // Struct to store birth date
    struct tm * timeinfo;
    // Inputs from user
    int year, month ,day;

    // Prompt user for date 
    printf ("Enter year: "); scanf ("%d",&year);
    printf ("Enter month: "); scanf ("%d",&month);
    printf ("Enter day: "); scanf ("%d",&day);

    // Set birth date
    time ( &birthtime );
    timeinfo = localtime ( &birthtime );
    timeinfo->tm_year = year - 1900;
    timeinfo->tm_mon = month - 1;
    timeinfo->tm_mday = day;
    birthtime = mktime ( timeinfo );

    diffSeconds = difftime(now, birthtime);
    printf("Seconds since birth: %d\n", (int)diffSeconds);
    printf("Minutes since birth: %d\n", (int)(diffSeconds/60));
    printf("Hours since birth: %d\n", (int)((diffSeconds/60)/60));
    printf("Days since birth: %d\n", (int)(((diffSeconds/60)/60)/24));
    printf("Months since birth: %d\n", (int)((((diffSeconds/60)/60)/24)/31));
    printf("Years since birth: %d\n", (int)(((((diffSeconds/60)/60)/24)/31)/12));

    return 0;
}
Last edited on
I really do appreciate you trying to help me and I 100% understand what you are trying to say about working off a library to improve/simplify my code now (which is what I originally thought.) The problem is, as I said earlier, the <time> library does not work before the year 1970 which makes my program completely useless for anyone that was born before then.

Seeing as how there are no other libraries (that I know of) which do the same thing, I chose to not include it. So yes I do see what you're saying, but I'm just pointing out that the TIME library itself is not going to work for how I wanted my program to work. I also searched for another library that would get around this but didn't find anything. In the end I thought it would just be much simpler and better practice to write my own.

By the way, I've pretty much gotten the entire class outline finished and it didn't take hardly any time at all. I am going to implement it but I've been more busy working on other stuff and reading into more advanced programming so I will update this thread when I get around to it. Most likely this will be in 3-5 days.
Last edited on
Well if that is the problem. Then find the difference between the current date and the birthdate, modified to last year, then add the difference in years from then to actual birth year represented in seconds.

i.e.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Set birth date
    timeinfo = localtime ( &birthtime );
    timeinfo->tm_year -= 1; // set to last year
    timeinfo->tm_mon = month - 1;
    timeinfo->tm_mday = day;
    birthtime = mktime ( timeinfo );

    diffYear = timeinfo->tm_year + 1900 - year;
    diffSeconds = difftime(now, birthtime);

    printf("Seconds since birth: %d\n", (((int)diffSeconds) + diffYear*31536000));
    printf("Minutes since birth: %d\n", (((int)(diffSeconds/60)) + diffYear*525600));
    printf("Hours since birth: %d\n", (((int)((diffSeconds/60)/60)) + diffYear*8760));
    printf("Days since birth: %d\n", (((int)(((diffSeconds/60)/60)/24)) + diffYear*365));
    printf("Months since birth: %d\n", (((int)((((diffSeconds/60)/60)/24)/31)) + diffYear*12));
    printf("Years since birth: %d\n", (((int)(((((diffSeconds/60)/60)/24)/31)/12)) + diffYear));
Topic archived. No new replies allowed.