Arrays

Arrays, also called tables and matricies( matrix), represent a grouping of like elements in a program under s single name.
  1. Declaring an array.

    name[count]

    int iaRainFall[12];
    char caVowels[5];
    float faInterestRates[20];
  2. Initializing an array
    An array may be populated with intial values when declared.

    int iaMonths[12]={31,28,31,30,31,30,31,31,30,31,30,31};

    You may omit the count if you supply initial values, The compiler will size the array

    char caVowels[]={'a','e','i','o',u');

  3. Accessing elements of array
    To acces an element of array you need to use a subscript. A subscript is an integer value between 0 and SIZE-1 of the array. The lower order subscript in C++ is zero.

    iaMonths[3] is 30.
    iaMonths[1]=29; // set Feb to 29 days.

    If you generate a subscript past the end of the array, it is not a syntax error. It is a run time error.
    A subscript can be any value that evaluates to an integer.
          int iIndex;
    
    	iIndex=4;
            cout << iaMonths[iIndex] <<endl;
            cout << iaMonths[iIndex+1] <<endl;
            cout << iaMonths[rand()%12] << endl;
    

  4. Passing arrays to functions.

    Arrays are always passed as an address of the first element.
    The length or number of elements is not passed.
    If the length is declared in the function it is only a comment.
    #include 
    #include 
    void f(int []);
    void g(int [3]);
    main()
    {
       int a[5]={4,5,6,7,8};
    
       f(a);
       g(a);
       return 0;
    }
    void f(int x[])
    {
     int i;
     for(i=0;i<5;i++) cout << x[i] " ";
     cout << endl;
     return;
    }
    void g(int x[3])
    {
     int i;
     for(i=0;i<5;i++) cout << x[i] << " ";
      cout << endl;
     return;
    }
    
    4  5  6  7  8
    4  5  6  7  8
    

  5. Multi-dimension arrays
    Arrays in C++ can contain more than one dimension. For example a checker board might be represented with:
    int board[8][8];
    

    To address individual cells you would need two subscripts like:
      board[3][4]=3;
      k=board[i][j];
    


    C++ does not allow the shorthand board[3,4]

    Multidimension arrays may be initialized like:
     int r[3][4]= {
                    {2,3,4,5},
                    {7,8,9,0},
                    {1,2,3,4}
                   };
    


    C++ allocates Multidimension arrays row major. When passing a two dimensional array the function must specify the value for the number of columns in a row.

    #include <iostream>
    #include <iomanip>
    void f(int [][4]);
    void main()
    {
      static int a[3][4]= {
                    {2,3,4,5},
                    {7,8,9,0},
                    {1,2,3,4}
                   };
    
    
       f(a);
    }
    void f(int x[][4])
    {
     int i,j;
     for(i=0;i<3;i++) {
        for(j=0;j<4;j++) 
            cout << setw(3) << x[i][j];
        cout << endl;
     }
    }
    
    
      2  3  4  5
      7  8  9  0
      1  2  3  4
    
    

  6. Accessing every element in an array
    A common task usually represented by the programming idiom.
        for(iIndex=0;iIndex<SIZE;iIndex++)
        {
               process each element
        }
    
    Like;
    
       for(iMonthNumber=0;iMonthNumber<12;iMonthNumer++)
           cout << iaMonths[iMonthNumber] << endl;
    
    

  7. Rewriting multiple case with arrays.
    Old Code
    void printHeading(int iMonth, int iYear)
    {
    	switch(iMonth) 
    	{
    		case 1 : cout << " January "; break;
    		case 2 : cout << "February "; break;
    		case 3 : cout << "  March  "; break;
    		case 4 : cout << "  April  "; break;
    		case 5 : cout << "   May   "; break;
    		case 6 : cout << "  June   "; break;
    		case 7 : cout << "  July   "; break;
    		case 8 : cout << " August  "; break;
    		case 9 : cout << "September"; break;
    		case 10: cout << " October "; break;
    		case 11: cout << " November"; break;
    		case 12: cout << " December"; break;
    	}
    	cout << " " << iYear <<endl;
    	cout << "---------------------" << endl;
    	cout << " S  M  T  W  T  F  S " << endl;
    	cout << "---------------------" << endl;
    }
    

    New Code
    void printHeading(int iMonth, int iYear)
    {
       string straMonthName[12]=={" January ", ,
    		              "February ",
    		              "  March  ",
    		              "  April  ",
    		              "   May   ",
    		              "  June   ",
    		              "  July   " ,
    		              " August  " ,
    		              "September" ,
    	                      " October " ,
    		              " November" ,
    		              " December" };
            cout << straMonthName[iMonth-1] << " " << iYear <<endl;
    	cout << "---------------------" << endl;
    	cout << " S  M  T  W  T  F  S " << endl;
    	cout << "---------------------" << endl; 
     }
    

    Old Code
    int getDaysinMonth(int iMonth,int iYear)
    {
     	int iValue;
    	switch(iMonth)
    	{
    		case 1 :
    		case 3 :
    		case 5 :
    		case 7 :
    		case 8 :
    		case 10:
    		case 12: iValue=31; break;
    		case 4 : 
    		case 6 :
    		case 9 :
    		case 11: iValue=30; break;
    		case 2 : if(leapYear(iYear)) iValue=29;
    			     else iValue=28;
    				 break;
    	}
    	return iValue;
    } 
    

    New Code
    int getDaysinMonth(int iMonth,int iYear)
    {
     	int iValue;
            int iaDaysinMonth[]={31,28,31,30,31,30,31,31,30,31,30,31};
            iValue=iaDaysinMonth[iMonth-1];
            if(iMonth == 2 && leapYear(iYear)) iValue++;
            return iValue;
    }
    

  8. Summing an array
    
         int iaNumbers[]={12,13,16,10,7,8,6,17};
         int iTotal,iIndex;
    
         iTotal=0;
         for(iIndex=0;iIndex<8;iIndex++) iTotal+= iaNumbers[iIndex];
    
  9. Finding maxima and minima
        int FindMax(int[], int);
        int FindMin(int[], int);
    
        int iaNumbers[10]={13,18,-2,4,5,-6,0,28,2,9};
    
        cout <<  "Maximum is " << FindMax(iaNumbers,10)  << endl;
        cout <<  "Minimum is " << FindMin(iaNumbers,10)  << endl;
    
    
    int FindMax(int iaArray[], int iSize)
    {
       int iValue, iIndex;
      
       iValue=iaArray[0];
       for(iIndex=1;iIndex<iSize;iIndex++)
         if(iaArray[iIndex > iValue) iValue=iaArray[iIndex];
       return iValue;
    }
    

  10. Arrays in structures or objects

    Structure or objects can include arrays as members.
    struct course
    {
     int   students;
     float average;
     int   grades[35];
    };
    
    course c;
    

    class course {
     private:
       int   students;
       float average;
       int   grades[35];
     public:
        member function prototypes;
    
    };
    
  11. Arrays of structures or objects

  12. Vectors
    Arrays are a programming tool that provide a mechanism to store a group of values under a single name. The values can be any available data type (e.g., int, double, string, etc.). In C++, we talk about vectors, rather than arrays.

    Vectors are declared with the following syntax:
        vector<type> variable_name (number_of_elements);
    

    Type refers to the data type of the elements of the array; variable_name is the name that we assign to the array, and the optional number_of_elements may be provided to indicate how many elements the array will contain.
    Examples of vector declarations are the following:
       vector<int>    x(5);     
       vector<double> y(20);   
    

    When we use vectors in our programs, we must provide, at the top of the file, the line:
        #include <vector>
    

    After a vector has been declared specifying a certain number of elements, we can refer to individual elements in the vector using square brackets to provide a subscript or an index just like an array.
    In the following example, the program asks the user for the grades for a group of 20 students and stores them in a vector:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main()
    {
         vector<double> grades(20);
    
         for (int i = 0; i < 20; i++)
         {
             cout << "Enter grade for student #" << i+1 << ": ";
             cin >> grades[i];
         }
    
         return 0;
    }
    

    Vectors have one important advantage with respect to arrays in C++: vectors can be resized during the execution of the program to accommodate extra elements as needed.

    In the example above, if we don't know in advance that there are 20 students, we could ask the user how many students are there, and resize the vector accordingly.
    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main()
    {
        vector<double> grades;
        int students;
    
        cout << "Number of students in this group: ";
        cin >> students;
    
        grades.resize(students);
    
        for (int i = 0; i < students; i++)
        {
            cout << "Enter marks for student #" << i+1 << ": ";
            cin >> grades[i];
        }
    
        return 0;
    }
    
    Notice that the valid subscripts for a vector with students elements are 0 to students-1.
    It's always a better idea to control for loops using the size() method of vector.
        for (int i = 0; i < grades.size(); i++)
    


    In some situations, we can't determine the number of elements before reading them. Vectors provide a convenient way of handling this type of situation. We can use the push_back() method to append one element at the end of the array. The operation includes resizing to one more element to accommodate for the extra element, and storing the given value at the end of the array.

    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main()
    {
        vector<double> grades;
        int number;
    
        cout << "Please enter the grades" << endl;
    
        while (cin >> number)
        {
            grades.push_back(number);
        } 
        cout << "Your entered " << grades.size() << " grades" <<endl;
        for (int i = 0; i < grades.size(); i++)
        {
            cout << "Student #" << i+1 << '\t' << grades[i] << endl;
        }
        system("Pause");
        return 0;
    }
    Please enter the grades
    78
    82
    68
    92
    98
    87
    88
    ^Z
    Your entered 7 grades
    Student #1      78
    Student #2      82
    Student #3      68
    Student #4      92
    Student #5      98
    Student #6      87
    Student #7      88
    Press any key to continue . . .
    

  13. Example Page 560 #4

    1. Header file monkey.h
      #ifndef  MONKEY
      #define MONKEY
      
      class monkey {
            private:
                    int day[7];
            public:
                   monkey();
                   void setDay(int=0,int=0);
                   int getDay(int=0);
                   int total();
      };
      #endif
      

    2. Implemenattion monkeymeth.cpp
      //
      // monkey methods
      //
      #include "monkey.h"
      
      monkey::monkey() // constructor
      {
         int i;
         for(i=0;i<7;i++) day[i]=0;
      }
      void monkey::setDay(int d, int food)
      {
           day[d]=food;
      }
      int monkey::getDay(int d)
      {
          return day[d];
      }
      int monkey::total()
      {
          int i, sum;
          
          sum=0;
          for(i=0; i<7; i++) sum+=day[i];
          return sum;
      }
      


    3. Main code monkey.cpp
      #include <cstdlib>
      #include <iostream>
      #include <iomanip>
      #include "monkey.h"
      
      using namespace std;
      
      
      int main()
      {
          string Day[]={"Sunday","Monday","Tuesday","Wednesday",
                        "Thursday","Friday","Saturday"};
          monkey ape[3];
          int i,j;
          int pounds;
          int least,most;
          
          for(i=0; i<3; i++) {
             cout << "Enter pounds of food for Monkey # " << i+1 << endl;      
             for(j=0;j<7;j++) {
                cout << "   " << Day[j] << " : ";
                cin >>pounds;
                ape[i].setDay(j,pounds);
             }
          }
      

          cout.setf(ios::fixed | ios::showpoint);
          cout.precision(2);
          cout << endl << "Average food consumed per day " << endl;
          for(j=0; j<7 ; j++) {
             float sum=0;
             for(i=0;i<3;i++) sum+=ape[i].getDay(j);
             cout << setw(12) << Day[j]  
                  << setw(8)  << sum/3 
                  << " pounds " <<endl;
          }     
          least=0;
          most=0;
          for(i=1;i<3;i++) {
            if(ape[i].total() < ape[least].total()) least=i;
            if(ape[i].total() > ape[most].total()) most=i;
          }
          cout << endl << "Most food consumed by Monkey # " << most
               << " " << ape[most].total() << " pounds " << endl;             
                           
          cout << endl << "Least food consumed by Monkey # " << least
               << " " << ape[least].total() << " pounds " << endl;              
          
          system("PAUSE");
          return EXIT_SUCCESS;
      }
      


    4. Output
      Enter pounds of food for Monkey # 1
         Sunday : 22
         Monday : 23
         Tuesday : 24
         Wednesday : 22
         Thursday : 23
         Friday : 25
         Saturday : 26
      Enter pounds of food for Monkey # 2
         Sunday : 31
         Monday : 32
         Tuesday : 33
         Wednesday : 32
         Thursday : 31
         Friday : 30
         Saturday : 20
      Enter pounds of food for Monkey # 3
         Sunday : 23
         Monday : 23
         Tuesday : 22
         Wednesday : 21
         Thursday : 20
         Friday : 26
         Saturday : 27
      
      Average food consumed per day
            Sunday   25.33 pounds
            Monday   26.00 pounds
           Tuesday   26.33 pounds
         Wednesday   25.00 pounds
          Thursday   24.67 pounds
            Friday   27.00 pounds
          Saturday   24.33 pounds
      
      Most food consumed by Monkey # 1 209 pounds
      
      Least food consumed by Monkey # 2 162 pounds
      Press any key to continue . . .