Introduction to C++: array

Embed Size (px)

Citation preview

  • 7/25/2019 Introduction to C++: array

    1/34

    Introduction to

    Object-Oriented Programming

    COMP2011: Array a Collection ofHomogeneous Objects

    Dr. Cecia ChanDr. Brian Mak

    Dr. Pedro SanderDr. Dit-Yan Yeung

    Department of Computer Science & EngineeringThe Hong Kong University of Science and Technology

    Hong Kong SAR, China{ kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.1

  • 7/25/2019 Introduction to C++: array

    2/34

    What is an Array?

    Arrayis a collection ofhomogeneous objects: objectsof thesametype. e.g. a

    collection of int, char, double,. . ., or user-defined types.

    Exception: The array elements

    cannot be reference variables.

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.2

  • 7/25/2019 Introduction to C++: array

    3/34

    Motivation from Programming Point of View

    A function to sort 3 integers can be:

    voidsort 3 int(int&x,int&y,int&z);

    A function to sort 6 integers can be:

    voidsort 6 int(int&u,int&v,int&w,int&x,int&y,int&z);

    How about a function to sort 10,000 integers? Are you going

    to create variable names for the 10,000 different integers?Arrayis designed to solve this problem: you only need oneidentifier nameto address all the 10,000 integers, and there isa way to refer to each of them.

    It can solve problems like: read a list of student names, andsort them in alphabetical order.

    In anExcel file, each column/row is basically anarrayso thatyou can do some common operations (like average, max, min,

    count) on it.{ kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.3

    http://www.cse.ust.hk/~mak/array-excel.xlshttp://www.cse.ust.hk/~mak/array-excel.xls
  • 7/25/2019 Introduction to C++: array

    4/34

    Part I

    1-Dimensional Array

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.4

  • 7/25/2019 Introduction to C++: array

    5/34

    C++ 1-Dimensional Array

    Syntax: Definitionof a 1D Array

    [ ] ;

    should be apositive constant. It can be a constantexpression too.

    Examples

    int number[10000]; // an array of 10,000 uninitialized integers

    const int NUM STUDENTS = 335;char gender[NUM STUDENTS]; // an array of 335 char

    floatscore[NUM STUDENTS + 1]; // an extra element to hold the mean

    intn = 3;double x[n]; // compilation error on VC++: size is NOT a constant

    intvalue[-4]; // compilation error: array size cannot be -ve

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.5

  • 7/25/2019 Introduction to C++: array

    6/34

    Subscripting: Access to Each Array Element

    ( if x is an int array, sizeof(int) = 4 )

    1000

    1004

    1008

    1000 + 4(N1)

    x[0]

    x[1]

    x[2]

    x[N1] 6

    588

    23

    19

    A 1Darrayis an ordered list ofelements.

    Successiveelements are stored incontiguous memory.

    To access an element, use thesubscript operator[ ]with anarray

    index.For an array of size N, the indicesrun from 0, 1, 2, . . . , N1.

    Each array element is treated like a

    regular variable:you may assign a value to ityou may assign its value toanother variableyou may pass it byvalueorreferenceto a function

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.6

  • 7/25/2019 Introduction to C++: array

    7/34

    Array and Control

    Arrayworks particularly well with loops: e.g. use a for-loop toaccess and manipulate each array element in turn.

    This is not a coincidence, but part of the C++languagedesign.

    Examples

    inty; // A regular int variable

    intx[3]; // An array of 3 int numbers

    x[0] = 34; // Array indices start from zero in C++x[1] = 289;x[2] = 75; // Index of the last element is 2 NOT 3!

    y = x[2]; // Now both y and x[2] are 75max(x[2], x[0]); // Pass array elements by valueswap(x[1], x[0]); // Pass array elements by reference

    for(int j = 0; j < 3; j++) // Triple each element of an arrayx[j] = 3;

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.7

  • 7/25/2019 Introduction to C++: array

    8/34

    Example: Manipulate an Array of Scores usingforLoop

    #include / array-mean.cpp /using namespace std;

    intmain(void){

    const int NUM STUDENTS = 5;floatscore[NUM STUDENTS];// Read in the first students score. Assume #student>= 1cin score[0];// Dont forget initializing the sum of scoresfloatsum score = score[0];

    for(int j = 1; j < NUM STUDENTS; ++j){

    cin score[j];sum score += score[j]; // Accumulate the scores

    }

    cout "mean score = " sum score/NUM STUDENTS endl;return 0;

    }{ kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.8

    S

  • 7/25/2019 Introduction to C++: array

    9/34

    Example: Manipulate an Array of Scores usingforLoop ..

    #include / array-max.cpp /using namespace std;

    intmain(void){

    const int NUM STUDENTS = 5;floatscore[NUM STUDENTS];// Read in the first students score. Assume #student>= 1cin score[0];floatmax score = score[0]; // Dont forget initializing the max score

    for(int j = 1; j < NUM STUDENTS; ++j){

    cin score[j];if (max score < score[j])

    max score = score[j];}

    cout "max score = " max score endl;return 0;

    }{ kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.9

    W S b i C R f S i F l

  • 7/25/2019 Introduction to C++: array

    10/34

    Wrong Subscript: Common Reason forSegmentation Fault

    C++ compiler does not automatically check that an arrayindex isout of bound.

    That is, for an array of size N, the compiler wont check if itis subscripted with an index between0and N1, neither atcompile-timenorrun-time.

    There is no compilation error for the following codes:

    intx[10]; x[-2] = 5; x[100] = 9;

    When the codes are run, x[-2] = 5; will put the value 5 to

    the memory space which is 24 bytes (size of 2 int)before

    the array x. Similarly, x[100] = 9; will put the value 9 to thememory space which is 904 bytesbeyondthe array.

    This is a common cause of therun-time errorcalledsegmentation fault your program trespasses into memorylocations that do not belong to it.

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.10

    A I i i li i

  • 7/25/2019 Introduction to C++: array

    11/34

    Array Initialization

    Just like anylocalvariable, when an array is defined, itselements are not initialized automatically.

    Syntax: DefineandInitializea 1D Array Simultaneously

    []= { , , . . . , };

    If there arefewervalues than the array size, the unspecifiedvalues will bezeros.

    It is acompilation errorif there aremorevalues than the arraysize.

    If you leave out the array size in the array initialization, thecompiler will count the number of initializing values and usesthat as the array size.

    Once defined, youcannotassign values to an array using theinitialization syntax.

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.11

    E l A I iti li ti

  • 7/25/2019 Introduction to C++: array

    12/34

    Example: Array Initialization

    inta[5] ={1, 2, 3, 4, 5};/ Same as

    int a[5];a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; a[4] = 5;

    /

    intb[5] = {1, 2}; // => {1, 2, 0, 0, 0}intc[5] ={}; // => {0, 0, 0, 0, 0}

    intd[ ] ={1, 2, 3}; // Compiler will determine the size automatically as 3

    inte[3];

    e ={5, 6, 7};// Compilation error: cant assign values to an array like this

    // Compilation error: cant declare an array of referencesdouble x = 1.5, y = 2.5, z = 3.5;int& s[ ] ={x, y, z};

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.12

    C Mi f A

  • 7/25/2019 Introduction to C++: array

    13/34

    Common Mis-uses of an Array

    While each array element can be treated as a simple variable, thewhole array, as represented by the array identifier, cannot.

    Examples: Correct and Incorrect Uses of Arrays

    int x[ ] = {1, 2, 3, 4, 5 };int y[ ] = {6, 7, 8, 9, 0 };int z[5];

    / Incorrect way /x = {5, 4, 3, 2, 1}; // Cannot assign to each array element

    // using the initialization syntaxx = 8; // x is not an integer! Its elements are.x += 2; // x is not an integer! Its elements are.x = y; // No assignment between 2 arraysz = x + y; // Cannot +, -, , / on the array name, but only its elements

    / Correct way; what does each for-statement do? /for (int j = 0; j < 5; ++j) x[j] = 5 - j;for (int j = 0; j < 5; ++j) x[j] = 8;for (int j = 0; j < 5; ++j) x[j] += 2;for (int j = 0; j < 5; ++j) x[j] = y[j];for (int j = 0; j < 5; ++j) z[j] = x[j] + y[j];

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.13

    P ss 1D A t F ti

  • 7/25/2019 Introduction to C++: array

    14/34

    Pass a 1D Array to a Function

    Examples: Arrays as Function Arguments

    / function header /float mean score(float score[ ], intsize) { . . . }float max score(float score[ ], intsize) { . . . }

    / inside the main() /float score[NUM STUDENTS];mean score(score, NUM STUDENTS);max score(score, NUM STUDENTS);

    Since thearray identifieralone does nottell us about its size,a function that operates on an array needs at least 2 inputarguments:

    thearray identifierthearray size(of typeint)

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.14

    Example: Pass an Array to a Function

  • 7/25/2019 Introduction to C++: array

    15/34

    Example: Pass an Array to a Function

    #include / array-mean-max-fcn.cpp /using namespace std;

    floatmean score(floatscore[ ], int size)

    { floatsum score = 0.0; // dont forget initializing the sum to zerofor (int j = 0; j < size; j++)

    sum score += score[j]; // accumulate the scoresreturn sum score/size;

    }

    floatmax score(float score[ ], int size){

    floatmax score = score[0]; // initialize the max score to that of the first studentfor (int j = 1; j < size; j++)if (max score < score[j])

    max score = score[j];return max score;

    }

    int main(void){

    const int NUM STUDENTS = 5;floatscore[NUM STUDENTS];

    for (int j = 0; j < NUM STUDENTS; j++)if (!(cin score[j])) return -1;

    cout "mean score = " mean score(score, NUM STUDENTS) endl;cout "max score = " max score(score, NUM STUDENTS) endl;return 0;

    }

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.15

    1D Array as a Functions Formal Parameter

  • 7/25/2019 Introduction to C++: array

    16/34

    1D Array as a Function s Formal Parameter

    While a regular variable may be passed to a function by valueor reference, an array variable is alwayspassed by value.

    However, although the array variable is passed by value, itselements are effectivelypassed by reference!

    Anychangeto an array element inside the function willpersisteven after the functionreturns.

    Just like a regular variable, you pass an array to a functionsimply by its variable name. e.g.

    max score(score, NUM STUDENTS);

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.16

    Example: Modifying Arrays Elements by a Function

  • 7/25/2019 Introduction to C++: array

    17/34

    Example: Modifying Array s Elements by a Function

    #include / array-add-rotate.cpp /using namespace std;

    void array add(int x[ ], int y[ ], int z[ ], int size)

    { for (int j = 0; j < size; j++)z[j] = x[j] + y[j];

    }

    void circular rotation(int x[ ], int size){

    int item 0 = x[0]; // save the first element before rotationfor (int j = 1; j < size; j++)

    x[j-1] = x[j]; // rotate upx[size - 1] = item 0; // fix the last element}

    void array print(int x[ ], int size){

    for (int j = 0; j < size; j++)cout x[j] \t;

    cout endl;}

    int main(void){

    int a[ ] = {1, 2, 3, 4}; int b[ ] = {11, 12, 13, 14}; int c[4];array add(a, b, c, 4); array print(c, 4); cout endl;

    for (int k = 0; k < 4; k++) { circular rotation(a, 4); array print(a, 4); }return 0;

    }

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.17

    Constant Array

  • 7/25/2019 Introduction to C++: array

    18/34

    Constant Array

    Just like simple constants, an array of constants can be made

    using the keyword const.const intx[ ] = { 1, 2, 3, 4 };

    It defines 4 integer constants: x[0], x[1], x[2], and x[3] are allof the typeconst int.

    Like simple constants, aconstant arraymust be initializedwhen it isdefined.once defined, its elementscannotbe modified.

    One main use of constant array is in the definition of theformal parameters of a function: to disallow modificationof

    theelementsof an array passed to a function, declare thatarray constant usingconst.

    inside the function, the array isread-only.however, the original array in the caller is still writable.

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.18

    Example: Prevent Modification by Constant Array

  • 7/25/2019 Introduction to C++: array

    19/34

    Example: Prevent Modification by Constant Array

    #include / const-array-mean-max-fcn.cpp /using namespace std;

    floatmean score(const float score[ ], int size)

    { floatsum score = 0.0; // dont forget initializing the sum to zerofor (int j = 0; j < size; j++)

    sum score += score[j]; // accumulate the scoresreturn sum score/size;

    }

    floatmax score(const float score[ ], int size){

    floatmax score = score[0]; // initialize the max score to that of the first studentfor (int j = 1; j < size; j++)

    if (max score < score[j])max score = score[j];

    return max score;}

    int main(void){

    const int NUM STUDENTS = 5;floatscore[NUM STUDENTS];

    for (int j = 0; j < NUM STUDENTS; j++)if (!(cin score[j])) return -1;

    cout "mean score = " mean score(score, NUM STUDENTS) endl;cout "max score = " max score(score, NUM STUDENTS) endl;return 0;

    }

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.19

  • 7/25/2019 Introduction to C++: array

    20/34

    Part II

    Multi-dimensional Array

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.20

    Array of any Dimensions

  • 7/25/2019 Introduction to C++: array

    21/34

    Array of any Dimensions

    In general, an array can be multi-dimensional.

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.21

    C++ 2-dimensional Array

  • 7/25/2019 Introduction to C++: array

    22/34

    C++ 2 dimensional Array

    Syntax: Definitionof a 2D Array

    [ ] [ ] ;

    int a[2][3] = {1,2,3,4,5,6}; // sizeof(int) = 4

    1000

    1004

    1008

    1012

    1016

    1020

    a[0][1] a[0][2]0

    a[1][1] a[1][2]

    a[0][0]

    a[0][1]

    a[0][2]

    a[1][0]

    a[1][1]

    a[1][2]

    0 1 2

    COLUMN

    1

    ROW

    2

    3

    6

    4

    5

    1

    a[0][0]

    a[1][0]

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.22

    Initialization of 2D Array

  • 7/25/2019 Introduction to C++: array

    23/34

    Initialization of 2D Array

    A2D arraycan be initialized in 2 ways:row by row, or

    like a 1D arraysince the array cells are actually stored linearlyin the memory.

    Examples

    / Initialize row by row /intpoint[5][2] = { // an int array with 5 rows and 2 columns

    {1, 1},{2, 4},{3, 9},{4, 16},{5, 25}

    };

    / Initialize using the fact that the cells of a 2Darray actually are stored linearly in the memory

    /intpoint[5][2] = { 1,1, 2,4, 3,9, 4,16, 5,25 };

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.23

    Example: Functions with 2D Array

  • 7/25/2019 Introduction to C++: array

    24/34

    p y

    #include / File: 2d-array-fcn.cpp /#include using namespace std;

    floatdistance(floatx1, float y1, float x2, float y2) {floatx diff = x1 - x2, y diff = y1 - y2;return sqrt(x diffx diff + y diffy diff);

    }

    void print 2d array(const float a[ ][3], int num rows, int num columns){

    for (int i = 0; i < num rows; i++) {for (int j = 0; j < num columns; j++) cout a[i][j] \t;cout endl;

    }}

    void compute all distances(const float point[ ][2], float dist[ ][3], int num points){

    for (int i = 0; i < num points; i++)for (int j = 0; j < num points; j++)

    dist[i][j] = distance(point[i][0], point[i][1], point[j][0], point[j][1]);}

    int main(void){

    floatdist[3][3]; // To store distances between any pairs of pointsfloat point[3][2] = { { 1.0, 1.0 } , { 2.0, 2.0 } , { 4.0, 3.0 } }; // (x, y) coordinates of 3 pointscompute all distances(point, dist, 3);print 2d array(dist, 3, 3);return 0;

    }

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.24

    C++ N-dimensional Array

  • 7/25/2019 Introduction to C++: array

    25/34

    ++ y

    Syntax: Definitionof an N-dimensional Array

    [] [] [] ;

    int a[2][2][2] = {1,2,3,4,5,6,7,8}; // sizeof(int) = 4

    a[0][0][0] a[0][0][1]

    a[0][1][0] a[0][1][1]

    0 1

    1

    0

    a[1][0][0] a[1][0][1]

    a[1][1][0] a[1][1][1]

    a[0][0][0]

    a[0][0][1]

    a[0][1][0]

    a[0][1][1]

    a[1][0][0]

    a[1][0][1]

    a[1][1][0]

    a[1][1][1]

    1000

    1004

    1008

    1012

    1016

    1020

    1024

    1028

    x

    z

    y

    2

    3

    6

    4

    5

    1

    7

    8

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.25

    Remarks on Multi-dimensional Array

  • 7/25/2019 Introduction to C++: array

    26/34

    y

    Although conceptually a 2D array is like a matrix, and a 3D

    array is like a cube, the elements of a multi-dimensional arrayarestored linearlyin the memory (just like a 1D array).

    In C++, the elements of a multi-dimensional array are storedinrow-major order: row by row.

    There are programming languages (e.g. FORTRAN) thatstore multi-dimensional array elements incolumn-major order:column by column.

    In row-major order, thelastdimension index runsfastest,

    while thefirstdimension index runsslowest.If a multi-dimensional array is used in a C++ function, alldimensions other than the first dimensionmust be specified inits declaration in the function header.

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.26

  • 7/25/2019 Introduction to C++: array

    27/34

    Part III

    C String: Special 1D Character Array

    h uk s t \0

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.27

    C String

  • 7/25/2019 Introduction to C++: array

    28/34

    g

    C++ follows Cs special way of representing a character string

    by a1D character array.

    Just add thenull character \0(ASCII code = 0)afterthelastcharacter of the string you need.

    h uk s t \0

    In general, if a string has a length ofN, add\0at the(N+ 1)th element of the char array.

    The\0acts as theend-markerfor a character string.

    C++ allows another notation using thedouble quotes. e.g.

    hkust = h k u s t \0

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.28

    Example: C String

  • 7/25/2019 Introduction to C++: array

    29/34

    #include / File: c-string.cpp /using namespace std;

    intmain(void){

    char s1[6] = {h, k,u,s,t, z};

    / At this point, s1 is still a simple char array /for(int j = 0; j < 5; j++)

    cout s1[j];cout endl;

    s1[5] = \0; / Now, s1 is a C string /cout s1endl;

    / Another notation for initialization, literal constant strings /char s2[20] = {h, k,u,s,t, \0}; cout "s2 = " s2endl;char s3[20] = "hkust"; cout "s3 = " s3 endl;return 0;

    }

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.29

  • 7/25/2019 Introduction to C++: array

    30/34

    Example: Functions with 2D Character Array

  • 7/25/2019 Introduction to C++: array

    31/34

    #include / File: str-array.cpp /using namespace std;

    void print strings(const char s[ ][16], int num of strings){for (int j = 0; j < num of strings; j++)

    cout s[j] " ";cout endl;

    }

    int main(void){

    // 5 C-strings, each having a max. length of 15 charconst char word[5][16] = {

    "hong kong","university","of","science","technology"

    };

    print strings(word, 5);return 0;

    }{ kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.31

    Reading C Strings withcin

  • 7/25/2019 Introduction to C++: array

    32/34

    cinwill skip all white spacesbefore reading data of therequired type until it sees the next white space.White spacesare any sequence of ,\tand\n.

    For charx; cin x; , if the input is hkust ,cinwillskipall theleading white spaces, and gives h to x.The same is true for reading a C string.

    For charx[20]; cin x; , if the input is hkust ,cin

    will skipall theleading white spaces, and gives hkust to x.Thus,cinis not good at readingmultiplewords or even aparagraph including possibly the newline. Instead, use:

    cin.getline(char s[ ], int max-num-char, char terminator);

    cin.getline( )will stop wheneither(max-num-char- 1)

    characters are read, OR, the terminating character terminatoris seen. The terminating character is removed from the inputstream but isnotread into the string.The C-string terminating null character is automaticallyinserted at the end of the read string.

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.32

    Example: cin.getline( ) from hacker.txt

    http://www.cse.ust.hk/~mak/hacker.txthttp://www.cse.ust.hk/~mak/hacker.txt
  • 7/25/2019 Introduction to C++: array

    33/34

    #include / File: read-str.cpp /using namespace std;

    intmain(void){

    const int MAX LINE LEN = 1000;char s[MAX LINE LEN+1];

    // read until the newline character (default)cin.getline(s, MAX LINE LEN+1, \n);cout s endl;

    // read until the character W

    cin.getline(s, sizeof(s), W);cout s endl;

    return 0;}

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.33

    Example: Palindrome

    http://www.rinkworks.com/words/palindromes.shtmlhttp://www.rinkworks.com/words/palindromes.shtml
  • 7/25/2019 Introduction to C++: array

    34/34

    #include / File: palindrome.cpp /using namespace std;

    bool palindrome(const char x[ ]){

    int j = 0; // An index reading the array from top (left)int k = strlen(x) - 1; // An index reading the array from bottom (right)

    for ( ; j < k; ++j, --k)if (x[j] != x[k])

    return false;return true;

    }

    int main(void){

    const int MAX LINE LEN = 255;char whole line[MAX LINE LEN+1];

    while (cin.getline(whole line, MAX LINE LEN+1, \n))cout boolalpha palindrome(whole line) endl;

    return 0;}

    { kccecia, mak, psander, dyyeung }@cse.ust.hk COMP2011 (Fall 2015) p.34