contoh array

Upload: nindhiapv

Post on 18-Oct-2015

29 views

Category:

Documents


0 download

DESCRIPTION

array

TRANSCRIPT

  • 5/27/2018 Contoh Array

    1/25

    Dale Roberts

    Department of Computer and Information Science,

    School of Science, IUPUI

    CSCI 230

    Arrays

    Dale Roberts, Lecturer

    IUPUI

    [email protected]

  • 5/27/2018 Contoh Array

    2/25Dale Roberts

    Arrays

    ArrayGroup of consecutive memory locations

    Same name and type, ex: an array of integers

    To refer to an element, specifyArray name

    Position number of particular element in the array

    Format:array_name[position number]

    First element at position 0nelement array named c:c[ 0 ], c[ 1 ]...c[ n 1]

    Example: int my_array[12]

    my_array[0]= -45 value storedPosition number must be an integer number or an

    integer expressionExample: my_array[1.5] ERROR!!

    my_array[i+j] valid ifiand j are integers

    Name of array (Note that all

    elements of this array have the

    same name,my_array)

    Position number of the elementwithin arraymy_array

    -45

    6

    0

    72

    1543

    -89

    0

    62

    -3

    1

    6453

    78

    My_array[0]

    My_array[1]

    My_array[2]

    My_array[3]

    My_array[4]

    My_array[5]

    My_array[6]

    My_array[7]

    My_array[8]

    My_array[9]

    My_array[10]

    My_array[11]

  • 5/27/2018 Contoh Array

    3/25Dale Roberts

    Arrays (cont.)

    Array elements are like normal variablesmy_array[8]= -3;printf( "%d", my_array[8]);

    Perform operations in subscript. If xequals 3:my_array[ 5 - 2 ] == my_array[ 3 ] == my_array[ x ]

    Declaring Arrays

    When declaring arrays, specify

    Name

    Type of array

    Number of elements: arrayType arrayName[ numberOfElements];

    Examples:int c[ 100 ];/* reserve memory sufficient enough to store

    100elements of type integer */

    float myArray[ 3284 ];

  • 5/27/2018 Contoh Array

    4/25Dale Roberts

    Arrays (cont.)

    Declaring multiple arrays of same type: format similar to regular variablesExample: int b[ 100 ], x[ 27 ];

    Arrays may be declared to contain other data typesExample: int a[ 100 ];

    float b[ 100 ];

    char c[ 100 ]; /* Strings are stored by using character arrays*/

    Example:

    #include /* a simple program that uses arrays */

    main(

    {

    int i, array_int[100];

    for (i=0; i

  • 5/27/2018 Contoh Array

    5/25Dale Roberts

    Arrays (cont.)

    Initializersint n[5] = {1, 2, 3, 4, 5};

    Example:main(){int i, a[10]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};for (i=0; i

  • 5/27/2018 Contoh Array

    6/25Dale Roberts

    1 /* Fig. 6.8: fig06_08.c

    2 Histogram printing program */

    3 #include

    4 #defineSIZE 10

    5

    6 intmain()

    7 {

    8 intn[ SIZE ] = { 19, 3, 15, 7, 11, 9, 13, 5, 17, 1 };

    9 inti, j;

    10

    11 printf( "%s%13s%17s\n", "Element", "Value", "Histogram" );

    12

    13 for( i = 0; i

  • 5/27/2018 Contoh Array

    7/25Dale Roberts

    Arrays (cont.)

    Example:

    #include

    #define SIZE 100

    main()

    {

    int i, a[SIZE];

    int sum = 0;

    for (i=0; i< size; i++)

    sum = sum + a[i];

    printf(sum: %d\n, sum);

    }

  • 5/27/2018 Contoh Array

    8/25Dale Roberts

    Character arrays

    String is really a static array of characters, ex: firstCharacter arrays can be initialized using string literals

    char string1[] = "first";

    Null character '\0'terminatesstrings

    string1actually has 6 elements

    It is equivalent to charstring1[]={'f','i','r','s','t','\0'};

    Can access individual charactersstring1[3] is character s

    Array name is address of array, so & not needed for scanf charstring2[20];

    scanf("%s",string2); /* can read a string with max of size19 and a

    null character*/

    Reads characters until whitespace (space, tab, carriage-return, newline,vertical tab) encountered

    Can write beyond end of array, be careful

    Character Arrays

    f i r s t \0

    Null character (indicates string termination)

    &is NOT used, why?

  • 5/27/2018 Contoh Array

    9/25Dale Roberts

    Passing Arrays to Functions

    Passing arrays

    To pass an array argument to a function, specify the name of the arraywithout any bracketsint myArray[24];

    ...

    myFunction(myArray,24);

    ...

    Array size usually passed to functionArrays passed call-by-reference

    the called functions can modify the element values in the callers originalarray

    Name of array is the address of first element of the array

    Function knows where the array is stored. Therefore, when the calledfunction modifies array elements in its function body, it is modifying theactual elements of array in the original memory locations

    Pass array name

    Size is also often sent as an argument

    myArray

    main()

    myFunction()

  • 5/27/2018 Contoh Array

    10/25Dale Roberts

    Passing Arrays to Functions (cont.)

    Example: #include main()

    {int a[10];printf(a = %p \n &a[0] = %p\n, a, &a[0]);}

    output: a = FFEE&a[0] = FFEE

    Passing array elements

    Individual elements of an array are passed by call-by-valuePass subscripted name (i.e.,myArray[3]) to function

    Example: compare(a[0], a[1]);

    An array is a vector while individual elements are scalars.

    Function prototypevoid modifyArray( int b[], int arraySize );

    Parameter names optional in prototype

    int b[]could be written int []

    int arraySizecould be simply int

    will be passed by value

  • 5/27/2018 Contoh Array

    11/25Dale Roberts

    1 /* Fig. 6.13: fig06_13.c2 Passing arrays and individual array elements to functions*/3 #include4 #defineSIZE 556 voidmodifyArray( int[], int); /* appears strange */

    7 voidmodifyElement( int);89 intmain()10 {11 inta[ SIZE ] = { 0, 1, 2, 3, 4 }, i;1213 printf( "Effects of passing entire array call "14 "by reference:\n\nThe values of the "15 "original array are:\n" );

    1617 for( i = 0; i

  • 5/27/2018 Contoh Array

    12/25Dale Roberts

    Function

    definitions

    33

    34 voidmodifyArray( intb[], intsize )

    35 {

    36 intj;

    3738 for( j = 0; j

  • 5/27/2018 Contoh Array

    13/25Dale Roberts

    Multiple-Dimensional ArraysMultiple subscripted arrays

    Arrays require at least two subscripts to identify a

    particular elementANSI C standard allows at least 12 array subscripts

    2D Arrays

    Tables with rows and columns (mby narray)Like matrices: specify row, then column

    Row 0Row 1Row 2

    Column 0 Column 1 Column 2 Column 3

    a[0][0]a[

    1

    ][

    0

    ]

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

    1

    ][

    1

    ]

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

    1

    ][

    2

    ]

    a[2][2]a[0][3]a[

    1

    ][

    3

    ]

    a[2][3]

    Row subscript

    Array nameColumn subscript

    A: scalar A[0]: 1D array

    1-Dimensional vector

    A[0][0]: (2 subscripts)

    2D array (matrix)

    2-dimensional vector

    A common error is to use

    math matrix notation a(1,2)

  • 5/27/2018 Contoh Array

    14/25Dale Roberts

    Multiple-Subscripted Arrays

    Initialization

    int b[2][2] = {{1,2},{3,4}};int c[3][2] = {{1,2},{3,4},{5,6}};

    Initializers grouped by row in braces

    If not enough, unspecified elements set to zeroint b[2][2]={{1},{3,4}};

    Referencing elementsSpecify row, then columnprintf("%d",b[0][1]);

    1 2

    3 4

    1 03 4

    1 2

    3 4

    5 6

    1 2 3 4 5 6Actual storage in the memory -

    rows by rows -row-major

    1 /* Fi 6 22 fi 06 22

  • 5/27/2018 Contoh Array

    15/25Dale Roberts

    1 /* Fig. 6.22: fig06_22.c

    2 Double-subscripted array example */

    3 #include

    4 #defineSTUDENTS 3

    5 #defineEXAMS 4

    6

    7 intminimum( constint[][ EXAMS ], int, int);

    8 intmaximum( constint[][ EXAMS ], int, int);9 doubleaverage( constint[], int);

    10 voidprintArray( constint[][ EXAMS ], int, int);

    11

    12 intmain()

    13 {

    14 intstudent;

    15 constintstudentGrades[ STUDENTS ][ EXAMS ] =

    16 { { 77, 68, 86, 73 },

    17 { 96, 87, 89, 78 },

    18 { 70, 90, 86, 81 } };

    19

    20 printf( "The array is:\n" );

    21 printArray( studentGrades, STUDENTS, EXAMS );

    22 printf( "\n\nLowest grade: %d\nHighest grade: %d\n",

    23 minimum( studentGrades, STUDENTS, EXAMS ),24 maximum( studentGrades, STUDENTS, EXAMS ) );

    25

    26 for( student = 0; student

  • 5/27/2018 Contoh Array

    16/25Dale Roberts

    33

    34 /* Find the minimum grade */

    35 intminimum( constintgrades[][ EXAMS ],

    36 intpupils, inttests )

    37 {

    38 inti, j, lowGrade = 100;

    39

    40 for( i = 0; i

  • 5/27/2018 Contoh Array

    17/25Dale Roberts

    65 inti, total = 0;

    66

    67 for( i = 0; i

  • 5/27/2018 Contoh Array

    18/25Dale Roberts

    Sorting Arrays

    Sorting data

    Important computing applicationVirtually every organization must sort some data

    Bubble sort (sinking sort)

    Several passes through the array

    Successive pairs of elements are comparedIf increasing order (or identical ), no change

    If decreasing order, elements exchanged

    Repeat

    Example:

    original: 3 4 2 6 7pass 1: 3 2 4 6 7

    pass 2: 2 3 4 6 7

    Small elements "bubble" to the top

    ase tu y: omput ng ean e an an

  • 5/27/2018 Contoh Array

    19/25Dale Roberts

    ase tu y: omput ng ean, e an anMode Using Arrays

    Meanaverage

    Mediannumber in middle of sorted listExample: 1, 2, 3, 4, 5 3 is the median

    Modenumber that occurs most oftenExample: 1, 1, 1, 2, 3, 3, 4, 5 1 is the mode

    1 /* Fig. 6.16: fig06_16.c

    2 This program introduces the topic of survey data analysis.

    3 It computes the mean, median, and mode of the data */

    4 #include

    5 #defineSIZE 99

    6

    7 voidmean( constint[] );

    8 voidmedian( int[] );9 voidmode( int[], constint[] ) ;

    10 voidbubbleSort( int[] );

    11 voidprintArray( constint[] );

    12

    13 intmain()

    14 {

    15 intfrequency[ 10 ] = { 0 };

    Function prototypes

  • 5/27/2018 Contoh Array

    20/25Dale Roberts

    33

    34 voidmean( constintanswer[] )

    35 {

    36 intj, total = 0;

    37

    38 printf( "%s\n%s\n%s\n", "********", " Mean", "********" );

    39

    40 for( j = 0; j

  • 5/27/2018 Contoh Array

    21/25

    Dale Roberts

    Define function median

    Sort Array

    Print middle element

    Define function mode

    Increase frequency[]

    depending on response[]

    65 }

    66

    67 voidmode( intfreq[], constintanswer[] )

    68 {

    69 intrating, j, h, largest = 0, modeValue = 0;

    70

    71 printf( "\n%s\n%s\n%s\n",

    72 "********", " Mode", "********" );

    73

    74 for( rating = 1; rating

  • 5/27/2018 Contoh Array

    22/25

    Dale Roberts

    95 printf( "\n" );

    96 }

    9798 printf( "The mode is the most frequent value.\n"

    99 "For this run the mode is %d which occurred"

    100 " %d times.\n", modeValue, largest );

    101}

    102

    80 printf( "%s%11s%19s\n\n%54s\n%54s\n\n",

    81 "Response", "Frequency", "Histogram",

    82 "1 1 2 2", "5 0 5 0 5" );

    83

    84 for( rating = 1; rating largest ) {

    88 largest = freq[ rating ];

    89 modeValue = rating;

    90 }91

    92 for( h = 1; h

  • 5/27/2018 Contoh Array

    23/25

    Dale Roberts

    126

    127 printf( "%2d", a[ j ] );

    128 }

    129 }

    103 voidbubbleSort( inta[] )

    104 {

    105 intpass, j, hold;

    106

    107 for( pass = 1; pass

  • 5/27/2018 Contoh Array

    24/25

    Dale Roberts

    Program

    Output

    Mean********The mean is the average value of the dataitems. The mean is equal to the total ofall the data items divided by the numberof data items (99). The mean value forthis run is: 681 / 99 = 6.8788

    ********Median

    ********The unsorted array of responses is7 8 9 8 7 8 9 8 9 7 8 9 5 9 8 7 8 7 86 7 8 9 3 9 8 7 8 7 7 8 9 8 9 8 9 7 8 96 7 8 7 8 7 9 8 9 2 7 8 9 8 9 8 9 7 5 35 6 7 2 5 3 9 4 6 4 7 8 9 6 8 7 8 9 7 87 4 4 2 5 3 8 7 5 6 4 5 6 1 6 5 7 8 7

    The sorted array is1 2 2 2 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 55 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 77 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8

    8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 89 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9 9

    The median is element 49 ofthe sorted 99 element array.For this run the median is 7

    ********Mode********Response Frequency Histogram

    1 1 2 25 0 5 0 5

    1 1 *2 3 ***3 4 ****4 5 *****5 8 ********6 9 *********7 23 ***********************8 27 ***************************9 19 *******************

    The mode is the most frequent value.For this run the mode is 8 which occurred 27 times.

  • 5/27/2018 Contoh Array

    25/25

    Dale Roberts

    Searching Arrays: Linear Search vs Binary Search

    Search an array for a key value

    Linear searchSimple

    Compare each element of array with key value

    Useful for small and unsorted arrays

    Binary searchFor sorted arrays

    Comparesmiddleelement with keyIf equal, match found

    If key < middle, looks in first half of array

    If key > middle, looks in last half

    Repeat

    Very fast; at most nsteps, where 2n> number of elements

    30 element array takes at most 5 steps

    25> 30 so at most 5 steps