Arrays

The next example uses an array to store the number of days in each month. The user can enter the number of a month and find out how many days are in the month. The array is declare to have 13 elements. They will be number 0 to 12. We won't be using element 0, but it is easier to understand if January is element 1 and December is element 12.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Months: print name of month and number of days.
#include<iostream>
#include<string>
using namespace std;
int main() {
  int days[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
  string month[13]={"","January", "February","March", "April",
    "May","June","July","August","September","October",
    "November", "December"};
  int mth; //to store user input
  cout<<"Enter the number of a month:";
  cin>>mth;
  if (mth<1 || mth>12)
    cout<<mth<<" is not a valid month.\n";
  else
    cout<<month[mth]<<" has "<<days[mth]<<" days.\n";
  system("pause");
  return 0;
} //main
CODE

Explanation:

  • An array can be given initial values. Something must be put in [0] in order for the other numbers to be in the right place.
  • Not everything is an array! Sometimes students learn about arrays and start making everything an array.
  • It is the programmer's responsibility to make sure that no attempt is made to use a subscript that is out of bounds.

NEXT: Find the day of the year