Docstoc

Arrays in

Document Sample
Arrays in Powered By Docstoc
					Arrays

ITK 169
Fall 2003



            1
                            Mars!
   Looking to the skies
    for the best view of
    the planet Mars in
    60,000 years.

        Source: (cnn.com)




                                    2
          What is an Array?
 A sequence of elements, all of the same type.
 The maximum number of elements must be

  known at compile time.
 Individual elements are accessed by an index

  (or subscript) which identifies their position
  in the array.



                                                   3
           Array Declaration
 Like other variables, arrays must be declared
  at the beginning of a function
 The declaration specifies the base type of

  the array, its name, and its size (dimension):

     int score[10];
     char grade[5];
     float price[20];


                                                   4
            Array Declaration
   We may use constants for the size in an
    array declaration:

    const int SIZE = 10;
    const int MAX_ELEMS = 15;

    int arr[SIZE];
    double flArr[MAX_ELEMS];

                                              5
 double temperature [5];

temperature [0]   12.3

temperature [1]   7.5

temperature [2]   65.0

temperature [3]   72.1

temperature [4]   87.5


                           6
 double temperature [5];

temperature [0]   12.3

temperature [1]   7.5

temperature [2]   65.0   Elements

temperature [3]   72.1

temperature [4]   87.5


                                    7
 double temperature [5];

temperature [0]   12.3

temperature [1]   7.5

temperature [2]   65.0   Subscript
                         or
temperature [3]   72.1   Index

temperature [4]   87.5


                                     8
       Printing the Array

cout<<temperature   [0];
cout<<temperature   [1];
cout<<temperature   [2];
cout<<temperature   [3];
cout<<temperature   [4];



                            9
        Printing the Array

for(int i=0; i<5; i++)
{
   cout<<temperature[i]<<endl;
}
                         Subscript Variable



                                              10
     Assignment Statement

temperature [4] = 12.7;

or

n = 4;
temperature [n] = 12.7;


                            11
               1. Assigning Values
   We cannot use assignment statements with
    entire arrays
       some languages allow this, but most, including
        C++, do not handle it.
   Instead, we must assign values to individual
    elements
        score[0] = 30;
        grade[3] = „A‟;
        price[2] = 10.39;
                                                         12
          Using Array Elements
   All of the following are valid:
    score[0] = 4;
    score[0] += 7;
    score[1] = score[0] -2;
    score[2] = score[1] + 5 * score[0];
    score[j] = score[j + 1];

   Note: index can be any integral expression.

                                                  13
    declaration:
    int score [6];




score:    49         75          65   90   77   70


index:      0             1       2    3   4     5


                score[2] = 65;
                score[0] = 49;


                                                     14
    Accessing the Individual Elements of
                  an Array
 If a variable represents an array, we refer to
  the whole array when we use just the name
  of the variable ex. score
 To get at a specific element of the array, a

  subscript, or an index, must be used to
  indicate which element we want to access.
 To get the element at index 3 in the score

  array, write:
       score[3]
                                                   15
    Accessing Individual Elements
 Subscripts (or indices) always start at 0
 Access a particular array element by using

  the array name followed by the index in
  square brackets:

     score[0]

     total = arr[9] + arr[0];

                                               16
                Be Very Careful!
   The most common programming error when using arrays
    is the attempt to reference a non-existent array index.

   The array definition
         int a[6];
    declares ONLY the indexed variables a[0] through a[5].

   An index value outside 0 to 5 is an out of range error.




                                                              17
        2. Declaration-Initialization
   Arrays can be initialized with values at declaration time

   We may list all of the values: they must all be constants.
       int num[5] = {58, 43, 60, 21, 38};

   The following will initialize the first element in the array to
    25, and all others to 0:
         int num[5] = {25};

   To initialize all elements of an array to 0
         int score_ary[10] = {0};

   We don‟t have to specify the dimension of the array when we
    initialize it:
          int x[ ] = {4, 8, 30, 21, 56, 87};
    will be an array of six elements
                                                                      18
      3. Enter from keyboard or file
   A for loop is an ideal way to read data into an
    array. This loop assumes we‟re reading
    exactly 5 elements.

      for (i = 0; i < 5; i++)
      {
         cout << “Please enter a score: ”;
         cin >> score[i];
       }

                                                      19
    What Do We Do with Arrays?
   The most common tasks we perform with
    arrays are to:
     Load information into an array for later
      processing
     Sort elements in a array

     Process each element of an array

     Search for a particular element in an array

     Write out the contents of an array



                                                    20
        Using Arrays with Functions
 We can pass individual array elements to
  functions either by value or by reference
 treat array elements same as other variables in
  the call
     prototype:
             void modifyElement(int num);
     call:

             modifyElement(arr[3]);
     function header:

              void modifyElement(int num)

                                                    21
        Arrays and Functions, cont.
   It‟s often useful to have a function which passes an
    entire array as a parameter
   You should always pass the size of the array also

   Prototype:
        void ReadScores(int score[], int NumPlayers);
   Call:
        ReadScore(score, NumPlayers);
   Header:
        void ReadScores(int score[], int NumPlayers)
                                                           22
        Arrays and Functions, cont.
   Once inside the function, handle the
    elements just as they are handled elsewhere:

    void ReadScores(int score[], int NumPlayers)
    {
        int i;
        for (i = 0; i < NumPlayers; i++)
        {
                cin >> score[i]);
        }
    }
                                                   23
                         Note!
 A function cannot return arrays
 When an array is passed to a function, its

  contents can be modified as if passed by
  reference.
 To keep the elements of an array from being

  accidentally modified in a function use the
  const keyword in the prototype and header:

    void PrintScores(const int score[],int numPlayers);


                                                          24
#include <iostream>
using namespace std;
                                        Finding the
int main()                              sum of
{                                       elements in
    int sum=0, i;                       an array
    int number[5] = {2, 4, 6, 8, 10};

    for (i=0; i<5; i++)
    {
           sum = sum + number[i];
    }

    cout<<"Sum ="<<sum;
    system("pause");
    return 0;

}
                                                      25
#include <iostream>
using namespace std;

int main()
                                        Finding the
{                                       largest
    int max, i;                         element in an
    int number[5] = {2, 4, 6, 8, 10};   array
    max = number[0];

    for (i=1; i<5; i++)
    {
           if (number[i]>max)
                    max = number[i];
    }

    cout<<"max ="<<max;
    system("pause");
    return 0;

}
                                                        26
#include <iostream>
using namespace std;
                                          Finding the
int main()
{
                                          index of the
    int index, i;                         largest
    int number[5] = {2, 4, 6, 8, 10};     element in an
                                          array
    index = 0;

    for (i=1; i<5; i++)
    {
          if (number[i]>number[index] )
                    index = i;
    }

    cout<<"max ="<<max;
    system("pause");
    return 0;

}                                                         27
                      Parallel Arrays
   Sometimes we have more than one piece of
    information to go in our array.
   For example, we might want an array of students
   Each one should have a ID number, an average, and
    a letter grade
   We would use three arrays
       an ID array
       an average array
       and a letter grade array
   The items found at a given index would all relate to
    the same student

                                                           28
                     Parallel Arrays

  ID_arr:    222      123     445     346     771    708

   index:        0        1       2       3    4     5



 avg_arr:    87.5     75.2    94.0    90.0    77.9   83.9

   index:        0        1       2       3    4     5



grade_arr:   B        C       A       A       C      B

   index:        0        1       2       3    4     5

                                                            29
    Arrays, Structures, and Classes
   Can use arrays with structures and classes
     array of structures
     array of classes

     structures with array member

     classes with array as data member




                                                 30
           Arrays of Structures
struct StudentInfo           to use members:
{
   int stu_id;               Our_class[1].stu_id = 123;
   double avg;
   char grade;               Our_class[0].grade = „A‟;
}
                             if (Our_class[10].avg > 89.5)
to declare:                  {
StudentInfo Our_class[40];      …..



                                                             31
              Arrays and Classes
   To declare an array of Money objects:
        Money amount[5];

   Remember that when an array of classes is declared, the
    default constructor is called to initialize the indexed
    objects

   To display one of the private members of the third Money
    object of the amount array, we would need to use its
    accessor function as follows:

      savings = amount[2].get_value();
                                                               32
         Multi-Dimensional arrays
 A multidimensional array has more than
  one dimension/index.
 Example:

  double sales [3][5];
       This declares a 2 dimensional array that has 3
        rows and 5 columns



                                                         33
    Multidimensional Arrays
   int data[3][5];


                            Columns

            data   0   1      2   3    4

               0   5   10 15 20 25
     Rows      1 30    35    40   45   50
               2 55    60    65   70   75
                                            34
Multidimensional Arrays
   int data[3][5];

    data[1][2]


                           2
                 5    10 15 20 25
           1 30       35   40   45   50
                 55   60   65   70   75
                                          35
     Example


int grade[4][3];


                   36
     Example


int grade[4][3];
       Students   Quiz


                         37
38
int grade[4][3];




                   39
#include <iostream>
#include <cstdlib>
using namespace std;

int main (void)
{
  int grade[4][3]= {10,10,10, 2, 0, 1, 8, 6, 9, 8, 4, 10};
  int i, j;

    for(i=0; i<4; i++)
    {
        for(j=0; j<3; j++)
        {
              cout<<grade[i][j]<<" ";
        }
        cout<<endl;
    }

    system("pause");
    return (0);
}                                                            40
41
            Multidimensional Arrays
   Another example of a multidimensional
       char page[30][100];

   This array has 30 rows and 100 columns.
   There are 30*100 indexed variables for this array.
   The indexed variables for this array are:
        page[0][0], page[0][0], . . . . page[0][99]
        page[1][0], page[1][1], . . . . page[1][99]
        page[2][0], page[2][1], . . . . page[2][99]
                .          .                   .
                .          .                   .
                .          .                   .
        page[29][0], page[29][1], . . . page[29][99]
                                                         42
      Multidimensional Arrays as
             Parameters
   When passing a multidimensional array into a
    function, the first dimension is not given a
    size, but the second MUST have the size.
    void myFunct(char page[ ] [ 100]);

   Remember, this array is passed by reference
    and changes will be returned to the calling
    function.

                                                   43
              Practice
        Given a Square Array
 Write a function to find the sum of the main
  diagonal of an array. (Pass the array in and
  hold it constant. Return the sum.)
 Change the function to find the sum of the
  second diagonal.
 Change the function to find the sum of a
  single row (passing in the index
      of the row).


                                                 44
45
#include <iostream>
#include <cstdlib>
using namespace std;

int main (void)
{
  int grade[4][3]= {10,10,10, 2, 0, 1, 8, 6, 9, 8, 4, 10};
  double quiz_ave[3]={0.0};
  double st_ave[4]={0.0};
  int i, j;

 for(i=0; i<4; i++)
 {
     for(j=0; j<3; j++)
     {
          st_ave[i] +=grade[i][j];
          quiz_ave[j]+=grade[i][j];
     }
 }

                                                             46
for(i=0; i<4; i++)
 {
     for(j=0; j<3; j++)
     {
       cout<<grade[i][j]<<"\t";
     }
     cout<<st_ave[i]/3.0<<endl;
 }
 for(j=0; j<3; j++)
     cout<<quiz_ave[j]/4.0<<"\t";

    system("pause");
    return (0);
}


                                    47
Results




          48
               Arrays
          and Class Objects
 Need practice problem for an array of
  objects
 Need practice problem for a class with an

  array member




                                              49
SolarSystem Array
   Source(cnn.com > NASA)




                            50
#include <iostream>
#include <cstdlib>

using namespace std;

int main (void)
{
  int ary[5][6];

    system("cls");

    cout << "The size of ary = " << sizeof(ary) << endl;
    cout << "The size of ary[0] = " << sizeof(ary[0]) << endl;
    cout << "The size of ary[0][0] = " << sizeof(ary[0][0]) << endl;

    system("pause");
    return (0);
}


                                                                       51
52

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:9
posted:11/12/2011
language:English
pages:52