chapter 9 - arrays - handout 1

Upload: zainabcom

Post on 03-Jun-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/13/2019 Chapter 9 - Arrays - Handout 1

    1/4

    1

    Chapter 9: Arrays

    Declaration//datatype array-name [size];int num[5]; declares an array of 5 int

    Accessing array components:

    num[0] = 12; //stores the value 12 in index 0 of num

    int i = 4; num[i] = 38; //stores 38 in num[4]

    num[2*i-5] =45; //stores 45 in num[3]

    num[1] = num[0]; //stores 12 in num[1]

    num[2] = num[0] + num[1];

    We can also use the following:const int size=10;

    int list[size];

    But rememberthat the size must be known before the runtime, i.e.

    int size;

    coutsize;

    int myList[size];illegal

    Array initialization during declarationchar M[3]={A, B, C};

    Declares an array of 3 char , and this is equivalent to saying:

    char M[ ]={A, B, C};

    but , we cant say: char M[]; // we must specify the size

    num[0]

    num[1]

    num[2]

    num[3]

    num[4]

    num[0] 12

    num[1] 12

    num[2] 24num[3] 45

    num[4] 38

    M[0] A

    M[1] B

    M[2] C

  • 8/13/2019 Chapter 9 - Arrays - Handout 1

    2/4

    2

    Partial assignment:int list[5]={1,2}; declares an array of 5 int, and initialize the first 2 elements to 1 and2, and set the rest elements to zero

    int list[10]={0};array of 10 int, and all elements equal to zero

    What is the different between the following two statements?int list[4]={2,1};

    int list[ ] = {2,1};

    The result of the first statement (int list[4]={2,1}; ) is:

    But, the result of the second statement (int list[ ] = {2,1};) is:

    What is the result of the following statement?

    char list[4]={a};

    Initialize list[0] to a, and the rest of elements will be space

    list[0] 1

    list [1] 2

    list [2] 0

    list [3] 0

    list [4] 0

    list[0] 2

    list [1] 1

    list [2] 0

    list [3] 0

    list[0] 2

    list [1] 1

    list[0] a

    list [1]

    list [2]

    list [3]

  • 8/13/2019 Chapter 9 - Arrays - Handout 1

    3/4

    3

    Processing one-dimensional Arrays

    Main operations used for arrays

    #include #includeusing namespace std;

    int main()

    {int size=3, index;

    double list[size], sum=0.0, average;

    cout

  • 8/13/2019 Chapter 9 - Arrays - Handout 1

    4/4

    4

    //finding the largest element in the array

    int maxIndex = 0;

    int max=list[0];for ( index=1; indexmax)

    {maxIndex = index;

    max = list[index];

    }

    cout