Arrays

This program finds the day of the year by adding together the number of days in each previous month. It uses several functions: A function to get the date, a function to determine if it is leap year, and another function to calculate the Julian date. The Julian date is the day of the year: January 1st is the 1st day; February 1st is the 32nd day. The date is checked for valid year, month and day.

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
// Finds Julian date for a valid month
#include<iostream>
using namespace std;
void getDate(int& mth, int& day, int& year);
bool validDate(int mth, int day, int year);
int julian(int month, int day); //finds day of year
void getDate(int& mth, int& day, int& year);
//Array is 13: 0..12, so Jan is [1] Dec. is [12], [0] not used
int days[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int main() {
  int mth, day, year;
  getDate(mth, day, year);
  if (validDate(mth, day, year))
    cout<<"Julian date="<<julian(mth,day)<<"\n";
  else
    cout<<"NOT a valid date\n";
  system("pause");
  return 0;
} //main
void getDate(int& mth, int& day, int& year) {
 char slash;
 cout<<"Enter a date as month/day/year:";
 cin>>mth>>slash>>day>>slash>>year;
} //getDate

bool leapYear(int year)  {//returns true if leap year
  bool leap=true;
  if (year%4) leap=false; //if year not div. by 4, not leap year
  if ((year%100==0) && (year%400>0)) leap=false;
  return leap;
} //leapyear

bool validDate(int mth, int day, int year) {
 bool valid=true;
 if (leapYear(year)) days[2]=29; else days[2]=28;
 if (mth<1 || mth>12) valid=false;
 else if(day<0 || day> days[mth]) valid=false;
 return valid;
} //validate
int julian(int month, int day) { //finds day of year
  int total, m;
  total=day; //May 21 is 21 + days in Jan.  April.
  for (m=0;m<month-1;m++)
  total+=days[m];
  return total;
} // julian
CODE

Another way to write this is to have the leap year function return 1 if it is leap year and 0 if not. The advantage is that instead of saying

if (leapYear(year)) days[2]=29; else days[2]=28;
You can say
days[2]=28+leapYear(year);

NEXT: Fast Food menu