Upgrade to Pro — share decks privately, control downloads, hide ads and more …

ics212-12-arrays

 ics212-12-arrays

William Albritton

October 07, 2015
Tweet

More Decks by William Albritton

Other Decks in Programming

Transcript

  1. Memory Allocation  Initialization  Using Arrays with Random Number

    Generator  Passing Arrays to Functions  Sorting Arrays  Searching Arrays  Multiple-subscripted Arrays
  2. Array Definition  An array is a numbered list of

    memory locations of the same name and type  Easy way to store lots of data  Static (doesn’t change in size)
  3. Array Index and Element  An array index is a

    non-negative integer that corresponds to the position of an array element  Indexes are numbered from 0, 1, 2, 3, 4, . . . N-1, where N is the size of the array  An array element is the value that is stored in an array at a specific index
  4. Array Initialization  Array initialization syntax:  datatype arrayName[SIZE] =

    {value};  We should always initialize our arrays to some value, otherwise the array may have “garbage values,” which are unpredictable values
  5. Initialize an Array to Zeros  Often use a predefined

    constant to store the size (number of elements) of the array #define SIZE 5 int main(){ int array1[SIZE]={0};
  6. Output an Array of Zeros  Typically, we use a

    for-loop to output the array elements for(i=0;i<SIZE;i++) { printf(“%d ”,array1[i]); } //output: 0 0 0 0 0
  7. Array Visualization  You can visualize an array as a

    group of boxes stacked on top of each other array1[4] array1[3] array1[2] array1[1] array1[0] 0 0 0 0 0
  8. Initializer List  Can also initialize all the elements to

    different values with an initializer list double array2[SIZE] = {1.1, 2.2, 3.3, 4.4, 5.5};
  9. Array Visualization  You can visualize an array as a

    group of boxes stacked on top of each other array2[4] array2[3] array2[2] array2[1] array2[0] 5.5 4.4 3.3 2.2 1.1
  10. Change the Elements  You can use a for-loop to

    change all of the elements in the arrays for(i=0;i<SIZE;i++) { array1[i] = i * 10; array2[i] = array2[i] * 10; }
  11. Array Visualization  You can visualize an array as a

    group of boxes stacked on top of each other array1[4] array2[4] array1[3] array2[3] array1[2] array2[2] array1[1] array2[1] array1[0] array2[0] 40 55.0 30 44.0 20 33.0 10 22.0 0 11.0
  12. Example Program  See example code at: initialize.c % cp

    initialize.c program.c % make –f makefile-program % ./program
  13. Seed the Random Number Generator  Use functions from <stdlib.h>

    & <time.h> libraries  Function time(NULL) gives time in seconds since January 1, 1970  Function srand( ) will seed (start off) the pseudorandom numbers srand(time(NULL));
  14. Create Random Numbers  x is the pseudorandom number 

    m is the shifting value (the 1st number in the range of integers)  n is the scaling factor (the width of the range of integers) x = m + rand() % n;
  15. Example Program  See example code at: random2.c  Simulates

    rolling one dice 1000 times  The array replaces the switch statement used in program random.c, so the code is much shorter! for(i=1;i<=MAX;i++){ side = 1 + rand() % 6; array[side]++; }
  16. Arrays = Pass by Reference  C passes arrays to

    functions by reference, so the function can modify the element values in the original array  The name of the array is actually the address of the first element of the array, so the function’s parameter contains a copy of the address of the array
  17. Array Elements = Pass by Value  Just like simple

    variables, the individual elements of an array are pass by value  The function’s parameter contains a copy of the value  The size of the array is also pass by value
  18. Parameter Syntax for Arrays  You have to use the

    square brackets for declaring array parameters, but NOT in function call  Function prototype: returnType functionName(datatype[]);  Function call: functionName(array);  Function definition: returnType functionName(datatype array[]); [ ]
  19. Example of Array Parameters  Function prototype  Array initialization

    and function call  Array element DOES need square brackets int array[SIZE]={1,2,3,4,5}; fun1(array, SIZE, array[0]); void fun1(int [], int, int);
  20. Function Definition void fun1(int a[], int max, int x){ int

    i = 0; x = 100; //assign a new value for(i = 0; i < max; i++) { a[i] = a[i] * a[i]; //multiply } }
  21. Example Program  See example code at: pass.c  Array

    is pass by reference, so elements are changed!  Individual array elements are pass by value, so no change for single element for(i = 0; i < SIZE; i++) { printf(“%d ”,array[i]);//1 4 9 16 25 }
  22. Sorting Arrays  Important topic in computer science  Need

    to be able to sort massive amounts of data  Bubble sort  Larger values “bubble” to the top of the array  Smaller values “bubble” to the bottom of the array  Think of a vertical array
  23. Bubble Sort  Algorithm for bubble sort  Pass through

    the array several times  With each pass, compare adjacent elements  If the pair is in increasing order (or identical), don’t swap  If the pair is in decreasing order, then swap
  24. Bubble Sort Code for(i = 0; i < size-1; i++){

    for(j = 0; j < size-1-i; j++){ if(a[j] > a[j+1]){ temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } }
  25. Example Program  See example code at:  bubble.c: driver

    program  arrayfunctions.c: has several array functions  arrayfunctions.h: header file with function prototypes  makefile-bubble: makefile to compile these files % make –f makefile-bubble % ./program
  26. Searching Arrays  If an array is sorted, then the

    high-speed binary search can be used:  Locate the middle element of the array and compare it to the search key  If equal, then the search key is found and the array subscript is returned  If not equal, then the upper half or lower half of the array is searched
  27. Binary Search  Why is binary search “high-speed”?  For

    example, an array of 1024 elements takes at most only 10 comparisons, with a Big-O of O(log n)  Searching 1024 elements reduces to 512, 256, 64, 32, 16, 8, 4, 2, and 1  1,048,576 elements takes only 20 comparisons  4,294,967,295 takes only 32 comparisons
  28. Binary Search Code while(first <= last){ halfway = (first+last)/2; if(target

    == array[halfway]){ return halfway;} else if(target < array[halfway]){ last = halfway - 1;} else{ first = halfway + 1; } }
  29. Example Program  See example code at:  search.c: driver

    program  arrayfunctions.c: has several array functions  arrayfunctions.h: header file with function prototypes  makefile-search: makefile to compile these files  getdouble.c and getdouble.h: number input % make –f makefile-search
  30. Multiple Subscripted Arrays  Multiple-subscripted arrays are also called multidimensional

    arrays  For example, a double-subscripted array (two dimensional array) can be used to represent a table of rows and columns
  31. Double Subscripted Arrays  For two dimensional arrays, think “RC

    Cola” for Row, then Column order  Initialization syntax: dataType arrayName[ROWS][COLUMNS] = {value}; int array[ROWS][COLUMNS] = {0};
  32. Function Prototype  Must have a value for 2nd subscript

    and higher in the function prototype: void printarray(int [][COLUMNS], const int, const int);
  33. Function Call  For the function call, only need the

    name of the array for multiple-subscripted arrays printarray(array, ROWS, COLUMNS);
  34. Function Definition  For the function definition, need to specify

    the 2nd subscript and higher void printarray(int array[][COLUMNS], const int rows, const int columns){ int i=0,j=0; for(i=0;i<rows;i++){ for(j=0;j<columns;j++){ printf(“%5d ”,array[i][j]); } printf(“\n”); } }
  35. Example Program  See example code at: multi.c  Initializes,

    displays, and changes the values of a two dimensional array
  36. Memory Management  Initialization  Using Arrays with Random Number

    Generator  Passing Arrays to Functions  Sorting Arrays  Searching Arrays  Multiple-subscripted Arrays