300 likes | 310 Views
CSCI 171. Presentation 10 Arrays. Array review. How do arrays work?. Assume we need a 12 element array to hold the total payroll (one element for each month). Declaring the array: float monthlyPayroll[12]
E N D
CSCI 171 Presentation 10 Arrays
How do arrays work? • Assume we need a 12 element array to hold the total payroll (one element for each month). • Declaring the array: • float monthlyPayroll[12] • Each of the 12 elements in monthlyPayroll() is a float, and can be treated like any float variable • Used in mathematical calculations • Passed to functions • Capture the return of a function • Other
How do arrays work? • Array review • Elements are stored in contiguous memory locations • In an array with n elements, valid subscripts are 0 to n–1 • For loops are useful to traverse arrays • Recall presentation 4 • int x[5]; causes the compiler to set aside memory:
Initializing Arrays • Assigning values at declaration time: • int x[5] = {100, 200, 300, 400, 500}; • Letting the compiler determine array size: • int x[] = {100, 200, 300, 400, 500}; • Too few initializers - Compiles fine • int x[5] = {100, 200, 300}; • Too many initializers - Compiler error • int x[5] = {100, 200, 300, 400, 500, 600};
The size of an array • Arrays are very powerful programming tools • Can be inefficient at run time • memory usage • searching can be time consuming • Size of array should be kept to minimum, or other data structures / concepts can be used • Pointers / dynamic memory allocation • User defined structures
The size of an array • Keep arrays as small as possible • Keep track of the size of an array • size = type size * number of elements • How much memory does a 100 element integer array use? • integers take 4 bytes in Code Warrior • 100 * 4 = 400 bytes
Data Types and Sizes • Type Size in bytes • ----------------------------------- • int 2 - 4 (4 in our system) • short 2 • long 4 • float 4 • double 8
How can size be determined? • Size of a type can be determined by sizeof • printf(“The size of an integer is %d”, sizeof(int)); • printf(“The size of the array x is %d”, sizeof(x)); • Valid arguments for sizeof function • Variables (simple data types, arrays) • Data types • Structures • Other
Multi-dimensional Arrays • Arrays with more than 1 subscript • 2 - D arrays have 2 subscripts • 3 - D arrays have 3 subscripts • ... • n - D arrays have n subscripts • Only available memory limits the number of dimensions available • Complexity increases exponentially with each added dimension
How do multi - dimensional arrays work? • int x[4][3] causes the compiler to assign 12 contiguous memory locations. • Visually, we can think of this as:
Multi-dimensional arrays • Each dimensional can be ‘visualized’ as a geometric object • 2 - D arrays can be thought of as squares • 3 - D arrays can be thought of as cubes • 4 - D arrays can be though of as a 4 dimensional object (hyper-cubes) • (insert Twilight Zone theme here) • 5 - D … (and so on) • In all cases, the data is simply stored in adjacent memory locations
Initializing multi-dimensional arrays • All values can be directly initialized: • int x[4][3] = {1 2 3 4 5 6 7 8 9 10 11 12} • Braces can be used to clarify each ‘row’: • int x[4][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10,11,12}}; • The idea of an ‘array of arrays’ extends from this form of initialization
Using for loops to initialize arrays • int x[1000]; • for (i = 0; i < 1000; i++) • x[i] = 1; • What does x look like after the loop executes?
Using for loops to initialize arrays • counter = 0; • int x[4][3]; • for (i = 0; i < 4; i++) • for (j = 0; j < 3; j++) { • x[i][j] = counter; • counter += 1; • } • What does x look like after the loop executes?
Order of elements in an array • int x[2][3][2] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} • implies the following: • x[0][0][0] = 1 x[1][0][0] = 7 • x[0][0][1] = 2 x[1][0][1] = 8 • x[0][1][0] = 3 x[1][1][0] = 9 • x[0][1][1] = 4 x[1][1][1] = 10 • x[0][2][0] = 5 x[1][2][0] = 11 • x[0][2][1] = 6 x[1][2][1] = 12
Arrays as Parameters • Passing by value • Passing the ‘value’ of the argument, but not the memory location • Simple data type arguments • Passing by reference • Passing the memory location • Array and pointer arguments • Allows the function to manipulate the variable in the calling program • Loss of data protection
Arrays as Parameters • Assume we want a function called test ( ) that accepts an integer array as its argument • prototype: • void test(int []); • function header: • void test(int data[]) • function call: • test(arrayName);
Arrays as Parameters #include <stdio.h> void init(float []); void print(float []); int main( void ) { float test[10]; init(test); print(test); } void init(float data[]) { int i = 0; for (; i<10; i++) data[i] = i; } void print(float data[]) { int i = 0; for (; i<10; i++) printf("%.2f ", data[i]); }
M-D Arrays as Parameters • Assume we want a function called test ( ) that accepts a M-D integer array as its argument • prototype: • void test(int [][10]); • note: Second dimension must be given • function header: • void test(int data[][10]) • note: Second dimension must be given • function call: • test(arrayName);
M-D Arrays as Parameters void init(float data[][10]) { int i = 0, j = 0; for (; i<10; i++) for (j=0; j<10; j++) data[i][j] = 0; } #include <stdio.h> void init(float [][10]); void print(float [][10]); int main( void ) { float test[10][10]; init(test); print(test); } void print(float data[][10]) { int i = 0, j = 0; for (; i<10; i++) { for (j=0; j<10; j++) printf("%.2f ", data[i][j]); printf(“\n”); } }
Why is 2nd dimension needed? • Assume we have a 2-d array: • int array[7][8]; • Which element is array [4][3]? • Element #4*8+3+1 = 36 • We needed the 8 to determine the element number, but did not need the 7 • Every dimension value is required except the first
Strings and Characters • Type char can only hold a single character • char x = ‘H’; • To hold a collection of 5 characters (i.e. a string), we need an array • char x[6] = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’}; • String - sequence of characters ending with a null character ( \0 )
Initializing Strings • char c[6] = {“HELLO”}; • char c[] = {“HELLO”}; • char c[] = “HELLO”; • char x[6] = {‘H’, ‘E’, ‘L’, ‘L’, ‘O’, ‘\0’};
Displaying strings • Can use either printf, or puts • char x[] = {“HELLO”}; • printf(“%s”, x); • puts(x);
Receiving strings as input • Can either use scanf, or gets • scanf only scans up to the first occurrence of whitespace (return key or a space) • char x[10]; • scanf(“%s”, x); // Notice no & is necessary • gets retrieves everything up to the return key • char x[10]; • gets(x);
String functions • Copying • strcpy(dest, source) • Concatenation • to append y onto the end of x: • strcat(x, y) • Comparing • strcmp(x, y) • returns a value < 0 if x < y • returns a value > 0 if x > y • returns a value = 0 if x = y