tablouri c

Upload: cristina-schuster

Post on 02-Jun-2018

236 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/10/2019 Tablouri c

    1/32

    Arrays

  • 8/10/2019 Tablouri c

    2/32

    2

    Introduction to Arrays

    An array is a list of elements of the same type storedcontiguously.

    Any array has a name (that is a constant pointer to thefirst element)

    The type of the elements is the type of the array

    Types: One-dimensional (vectors in C)

    Multi-dimensional

  • 8/10/2019 Tablouri c

    3/32

    3

    One-dimensional arrays (vectors - C) Declaration:

    type array_name[dim];

    type is a data type (predefined or user defined)

    array_name is an identifier

    [ ]is a delimitation

    dim is a positive integer constant expressionthat specifies thenumber of elements

  • 8/10/2019 Tablouri c

    4/32

    4

    To access an element we use the index operator [ ],specifying the array_nameand the position in the array

    by an index:array_name [index]

    indexis a positive integer expression

    First element has the index 0 and the last element,index (dim-1)

  • 8/10/2019 Tablouri c

    5/32

    5

    Considering the number and the type of the arrayelements the compiler will determine the allocationdimension by:

    dim_memory = sizeof(type) * dim

    Example:

    int tab[100];

    first element:tab[0]

    last element (100):tab[99]

    the i+1 element:tab[i]

    allocation sizeof(int)*100 = 2(4)00

  • 8/10/2019 Tablouri c

    6/32

    6

    After allocation the compiler will not verify the index

    range: tab[200]will not be an error at the execution, but error as data

    processing

  • 8/10/2019 Tablouri c

    7/32

    7

    Remarks:

    1. The specified dimension must be an integerconstant:

    const int SIZE = 10;

    int score[SIZE/2];

    2. It is not allowed as dimension an expression withvariables:

    int size;

    cout > size;

    int score[size]; // incorect !

    3. An array declaration may appear anywhere where

    are declared variables of the same type:

    int i, score[5], x, y, z;

  • 8/10/2019 Tablouri c

    8/32

    8

    Declaration:

    type array_name [dim1][dim2]...[dimN];

    To refere an element: array_name [index1][index2]...[indexN];

    If n=2 we have a matrix Example: float tab[10][5];

    In C/C++ we have no restrictions concerning the number ofdimensions for a multi-dimensional array.

    Multidimensional arrays

  • 8/10/2019 Tablouri c

    9/32

    9

    A multidimensional array is a one-dimensional array

    that as elements has arrays

    Example:

    int tab[2][3];

    is an array with 2 elements each element is a one-dim array of 3 intnumbers.

    Logical structure:

  • 8/10/2019 Tablouri c

    10/32

    10

    Memory structure:

    The access to an element:

    array_name[index1][index2]...[indexN]

    0 tab[0][0]

    1 tab[0][1]

    2 tab[0][2]

    3 tab[1][0]

    4 tab[1][1]

    5 tab[1][2]

  • 8/10/2019 Tablouri c

    11/32

    11

    4.Array elements An array element may appear anywhere where may

    appear a simple variable of the same type:

    assign:

    tab[i] = 23;

    KB input:

    cin >> tab[i];

    scanf(%d, &tab[i]); output:

    cout

  • 8/10/2019 Tablouri c

    12/32

    12

    5. Declaration init arrays

    If are not explicit initialized the local arrays elements are

    undefined

    The init process may be realized at the declaration by

    using a list of values separated by comma, between

    curly braces.

  • 8/10/2019 Tablouri c

    13/32

    13

    One dimensional arrays:

    type array_name[dim] = {ec0, ..., ecN-1};

    If dimis not specified the number of constant expressions will

    give the array dimension

    If dimis specified, the elements that are not explicit init will be 0

    For character strings the curly braces may be omitted

    Examples:

    int tab[ ] = {1,3,5,7,9,11};

    float tab[5] = {0,1,2};char tab[ ] = "abcd";//4 elements and \0

  • 8/10/2019 Tablouri c

    14/32

    14

    Multidimensional arrays:

    type name[n][m]= {

    {ec11,...,ec1m},

    {ec21,...,ec2m},...,

    {ecn1,...,ecnm}

    };

    where: n, m, ecij, are constant expressions (indexes from 0to n-1,respective from 0to m-1)

    Inside, curly braces may be omitted, but if we consider, will

    specify the row init process

    Example:

    int tab[3][2] = { {10,11},

    {12,13},

    {14,15} };

  • 8/10/2019 Tablouri c

    15/32

    15

    6. Array elements processing

    It is preferred the anterior recursive instruction for()because we know the number of elements that aresequential processed: The cycle variable is used as array index

    Other variable or a symbolic constant that represents the arraydimension is used in the associate condition

  • 8/10/2019 Tablouri c

    16/32

    16

    One-dimensional arrays:

    for (int i=0; i> temperature[i];

    for (int i=0; i

  • 8/10/2019 Tablouri c

    17/32

    17

    Bidimensional arrays:

    for (int row = 0; row < 10; row++)

    for (int col = 0; col < 10; col++)

    {

    cout

  • 8/10/2019 Tablouri c

    18/32

    18

    Example bidimensional array: main diagonal sum

    int arr[10][10];

    int sum = 0;

    for (int row = 0; row < 10; row++)

    for (int col = 0; col < 10; col++)if (row == col)

    sum += arr[row][col];

    cout

  • 8/10/2019 Tablouri c

    19/32

    19

    7. Arrays as function parameters An array may be transferred as parameter to a function.

    In this case: Formal parameter is declared as an array with same type and

    dimension with the array used as argument

    Formal parameter is declared as an array where the first (left)dimension may be ignored

    Formal parameter is declared as a pointer to the array type

    In any case as argument we use the array address

    At one-dimensional arrays we may consider asparameter an array with no dimension.

    Usual in this case we have other parameter that

    represents the array dimension, that is an intvariable

  • 8/10/2019 Tablouri c

    20/32

    20

    // prototype

    void read_data(int score[ ], int size);

    // definition

    void read_data(int score[ ], int size)

    {

    for (int i=0; i> score[i];

    }

    // callint tab1[120], tab2[110];

    read_data(tab1,120);

    read_data(tab2,110);

  • 8/10/2019 Tablouri c

    21/32

    21

    In the calling process the first parameter is named array

    parameter (first element address)

    Such a calling mechanism is an address calling that will

    specify everything about the array, without the

    dimension.

    Using this parameter and the index element it is possible

    to calculate the address of any element from the array

    In this mode any operation concerning the array realized

    inside the function will be visible outside

  • 8/10/2019 Tablouri c

    22/32

    22

    We may use a constmodifier to the array so that we are

    not able to modify the array elements:void displayArray ( const int arr [ ], int MAXSIZE );

    For multidimensional arrays, the first dimension (left)

    may be omitted concerning the allocation mechanism ofan array in C:

    void display(char p[ ][100], int size)

  • 8/10/2019 Tablouri c

    23/32

    23

    const int SIZE=5;

    double calcAvg (double numbers[ ], int max);

    void printArray(double[ ], int);

    void main( )

    {

    double temps[SIZE];

    int index;

    double avg;

    cout

  • 8/10/2019 Tablouri c

    24/32

    24

    double calcAvg (double numbers[ ], int count)

    {

    double sum=0;

    for (int i=0; i

  • 8/10/2019 Tablouri c

    25/32

    25

    7. Searching elements in an array

    It is a very frequent operation

    Usual we search the position of an element with acertain value

    If array is not sorted we use a linear search algorithm:

    A sequential elements crossing is realized with the comparison

    with the searched value If a value is found, the index element is returned, otherwise

    value -1 is returned

    The algorithm will find the first occurrence of the value

  • 8/10/2019 Tablouri c

    26/32

    26

    int linear_search(int arr[ ], int n, int val)

    {

    int pos;for(pos = 0; pos < n; pos++)

    if (arr[pos] == val)

    return pos;

    return -1;

    }

    For small arrays the algorithms is Ok

  • 8/10/2019 Tablouri c

    27/32

    27

    Binary search:

    We verify if the middle element is the searched value If yes, we return the position

    If no, we search to left or right side

    We continue the process till we find an element or the

    interval is null

  • 8/10/2019 Tablouri c

    28/32

    28

    // we supose that the array is increasing sorted

    int binarySearch(int arr[ ], int size, int target)

    { int middlePosition, middleValue;

    int low = 0, high = size - 1;

    while (low

  • 8/10/2019 Tablouri c

    29/32

    29

    8. Insert an element in the array For unsorted arrays, to insert a new element we must

    consider: Must exist space in the array;

    The new element will determine a usual right shifting of some

    array elements

    For sorted arrays, we first must find the position where to

    insert the new value so that the array will remain sorted

  • 8/10/2019 Tablouri c

    30/32

    30

    Unsorted arrays

    void insert_at(int arr[ ], int n, int idx, int val){

    if (idx == -1)

    arr[n] = val; // adaugare

    else

    {

    // deplasare dreapta

    for(int i = n; i > idx; i)

    arr[i] = arr[i-1];

    // inserare valoare noua

    arr[idx] = val;

    }

    }

  • 8/10/2019 Tablouri c

    31/32

    31

    Sorted arrays

    void insertElement ( int arr [ ], int &size, int newElement )

    {int insertPosition, k;

    // cautare pozitie inserare

    insertPosition = -1;do

    insertPosition++;

    while ( newElement > arr[insertPosition] && insertPosition != size - 1 );

    if ( newElement = insertPosition; k-- )arr[k+1] = arr[k];

    // inserarearr[insertPosition] = newElement;

    }else

    arr[size] = newElement; // adaugaresize++;//se va vedea si in exterior

    }

  • 8/10/2019 Tablouri c

    32/32

    32

    9. Delete arrays element As to insert, to delete will impose usual left shifting of

    some array elements

    We suppose that we know where we delete the element,otherwise a searching algorithm will be used

    void deleteElement ( int arr [ ], int &size, int position )

    //size is reference to have the modified value outside{

    int k;

    if ( position >= size )cout