Arrays I Handling lists of data CMSC 104 1 Arrays A data structure is a group of related data items. The array is one kind of data structure. An array is a group of related data items that all have the same name and the same data type. Arrays are static in that they remain the same size throughout program CMSC 104 execution. 2 Arrays An array is a sequence of data items, all of the same type that are stored contiguously in memory. Each of the data items is known as an element of the array We can access the individual elements of the array using an indexing scheme Arrays can be of any type we choose. CMSC 104 3 Array Declarations int array [5] ; This declaration sets aside a chunk of memory that’s big enough to hold 5 integers. It does not initialize those memory locations to 0 or any other value. Initializing an array may be done with an array initializer, as in : int array [5] = { 5, 2, 6, 9, 3 } ; array CMSC 104 5 2 6 9 3 0 1 2 3 4 4 Indexing Array Elements Values of individual elements can be found by indexing into the array. In our example, array [0] is equal to 5 and array [3] is equal to 9. The integer in square brackets is called the subscript. The subscript could also be an expression that evaluates to an integer. In our example, array is the name of the CMSC 104 array. 5 Modifying Elements Individual elements of the array can also be modified using subscripts. array [4] = 20 ; /*changes the value of the element found at subscript 4 to 20 */ Values may be stored in an array using indexing, rather than using the array initializer. CMSC 104 6 Filling Arrays Since many arrays are quite large, using an array initializer is impractical. Large arrays are often filled using a for loop. for ( i = 0; i < 100; i++) { rolls [ i ] = 0 ; } would set every element of the 100 CMSC 104 element array, rolls, to 0. 7 More Declarations int score [39] , gradeCounter [5]; Declares two arrays of type int Neither array has been initialized score contains 39 elements (one for each student in the class) gradeCounter contains 5 elements (one for each possible grade, A-F) CMSC 104 8 Using #define for array sizes We often use the #define to give the sizes of arrays. #define SSIZE 39 #define GSIZE 5 main ( ) { int score [SSIZE] ; int gradeCounter [GSIZE] ; } CMSC 104 9