1 / 40

ECET 264 C Programming with Applications

ECET 264 C Programming with Applications. Lecture 11 C Arrays and Applications Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin. Lecture 11 – Array Applications. Determine Size of Arrays Passing Arrays to Functions Searching Arrays

adler
Download Presentation

ECET 264 C Programming with Applications

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ECET 264 C Programming with Applications Lecture 11 C Arrays and Applications Paul I. Lin Professor of Electrical & Computer Engineering Technology http://www.etcs.ipfw.edu/~lin Paul I Lin

  2. Lecture 11 – Array Applications • Determine Size of Arrays • Passing Arrays to Functions • Searching Arrays • Multiple Subscripted Arrays • Programming Applications Paul I Lin

  3. Determining the Sizes and Bounds of Arrays Array size • Must be determined at design time • Array boundary must be checked at run-time • sizeof operator Examples Determine the size of LCD array • sizeof(display_LCD)/sizeof(char) Determine the size of data array • sizeof(data)/sizeof(int) Paul I Lin

  4. Example 11 - 1 /* while0.c - Accessing data arrays using a while() loop and describe out of boundary*/ #include <stdio.h> // define format string #define FORMAT "data[%d] = %d,\ d[%d] = %d\n", i,data[i],i,d[i] #define N 6 static int data[] = { 1,2,3,4,5,6 }; // static array definition void main() { int d[N], i, j, k; i = 0; j = 1; k = 2; Paul I Lin

  5. Example 11 – 1(continue) while(i < N) { d[i] = data[i] * 2; printf(FORMAT); i++; } /* Try access the array outside its boundary */ printf(FORMAT); // printf("data[%d] = %d,\ d[%d] = %d\n", i,data[i],i,d[i]) i++; printf(FORMAT); } Paul I Lin

  6. Example 11 - 1(continue) Output: data[0] = 1, d[0] = 2 data[1] = 2, d[1] = 4 data[2] = 3, d[2] = 6 data[3] = 4, d[3] = 8 data[4] = 5, d[4] = 10 data[5] = 6, d[5] = 12 data[6] = 1635017060, d[6] = 6618680 data[7] = 1566844251, d[7] = 4199065 Paul I Lin

  7. Passing arrays to functions • To pass an array to a function - the name of the array is passed • To pass a single element of an array to a function - simply pass the name of the array followed by the subscript of the particular element. • C passes arrays to functions by reference – the called functions can modify the element values in the caller’s original arrays. • The name of the array is actually the address of the first element of the array Paul I Lin

  8. Passing arrays to functions(continue) • When the called function modifies array elements in its function body, it is modifying the actual elements of the array in their original memory location. • To receive an array argument, the function’s parameter list must specify that an array will be received. The size of that array is also needed. An example: int findmax(int this_array[ ], int size); int findmax(int *this_array, int size) Paul I Lin

  9. Example 11 - 2 /*A simple program uses functions for swapping and printing data elements in a two-dimensional array. */ #include <stdio.h> void swap(int *, int *); /* Function Prototypes */ void print(void); /* Function Prototypes */ static int data[2][2] = { {1, 2}, {3, 4}}; void main() { int x, y; puts("\nBefore swapping"); print(); swap(&data[0][0], &data[1][1]); swap(&data[0][1], &data[1][0]); puts("\nAfter swapping"); print(); } Paul I Lin

  10. Example 11 - 2(continue) void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } void print(void) { int r, c; for(r = 0; r < 2; r++) for(c = 0; c < 2; c++) { printf("\ndata[%d][%d] = %d",r,c,data[r][c]); } } Paul I Lin

  11. Example 11 - 2(continue) Output: Before swapping After swapping data[0][0] = 1 data[0][0] = 4 data[0][1] = 2 data[0][1] = 3 data[1][0] = 3 data[1][0] = 2 data[1][1] = 4 data[1][1] = 1 Paul I Lin

  12. Example 11 - 3 /* Passing arrays and individual array elements to functions */ #include <stdio.h> #define SIZE 5 /* function prototypes */ void modifyArray( int b[], int size ); void modifyElement( int e ); /* function main begins program execution */ int main() { int a[ SIZE ] = {0, 1, 2, 3, 4}; /* initialize a */ int i; /* counter */ Paul I Lin

  13. Example 11 - 3(continue) printf( "Effects of passing entire array by reference:\n\nThe " "values of the original array are:\n" ); /* output original array */ for ( i = 0; i < SIZE; i++ ) { printf( "%3d", a[ i ] ); } /* end for */ printf( "\n" ); /* pass array a to modifyArray by reference */ modifyArray( a, SIZE ); printf( "The values of the modified array are:\n" ); Paul I Lin

  14. Example 11 - 3(continue) /* output modified array */ for ( i = 0; i < SIZE; i++ ) { printf( "%3d", a[ i ] ); } /* end for */ /* output value of a[ 3 ] */ printf( "\n\n\nEffects of passing array element " "by value:\n\nThe value of a[3] is %d\n", a[ 3 ] ); modifyElement( a[ 3 ] ); /* pass array element a[ 3 ] by value */ /* output value of a[ 3 ] */ printf( "The value of a[ 3 ] is %d\n", a[ 3 ] ); return 0; /* indicates successful termination */ } /* end main */ Paul I Lin

  15. Example 11 - 3(continue) /* in function modifyArray, "b" points to the original array "a" in memory */ void modifyArray( int b[], int size ) { int j; /* counter */ /* multiply each array element by 2 */ for ( j = 0; j < size; j++ ) { b[ j ] *= 2; // b[ j ] = b[j ] * 2; } /* end for */ } /* end function modifyArray */ /* in function modifyElement, "e" is a local copy of array element a[ 3 ] passed from main */ void modifyElement( int e ) { /* multiply parameter by 2 */ printf( "Value in modifyElement is %d\n", e *= 2 ); } /* end function modifyElement */ Paul I Lin

  16. Example 11 - 3(continue) Paul I Lin

  17. Sorting Elements in Arrays • Sorting is the process of rearranging the elements of an array into numerical order (either ascending or descending). • Bubble sort, Selection sort, Quick sort, etc • Min, Max elements • Help data analysis Paul I Lin

  18. Sorting Elements in Arrays • After the sorting • min = a[ 0 ] – smallest element • Max = a[size -1] -- largest element • Middle element • Using bubble sort (sinking sort) – the smaller value upward to the top while the larger values sink to the bottom of the array • Bubble sort is performed by the two nested for loops and a swap function Paul I Lin

  19. Sorting Elements in Arrays • Bubble Sort • Before sorting • d_array = [76 45 1 82 44] • After sorting • d_array = [1 44 45 76 82] • Steps (repeated until no swaps take place) • If the first element of x is greater than the second element of x, swap their positions in the vector. • If the second element of x is greater than the third element of x, swap their positions in the vector. • · · · · · · · · · • If the next-to-last element of x is greater than the last element of x, swap their positions in the vector Paul I Lin

  20. Bubble Sort – Example 11-4 /* bubblesort.c */ #include <math.h> #include <stdio.h> #define MAX 10 int no[MAX]; unsigned long int next = 1; /* rand(): return psedo-random integer from 0...32767 */ int rand(void) { next = next * 1103515245 + 12345; return (unsigned int) (next/65536) % 32768; } /* srand: set seed for rand() */ void srand(unsigned int seed) { next = seed; } Paul I Lin

  21. Bubble Sort – Example 11-4(cont.) void sort(int data[], int size) { int upper, lower, temp; // Loop for counting the number of passes for(upper = 0; upper < size -1; upper++) { // Loop for comparison and exchange for(lower = upper + 1; lower < size; lower++) { if(data[upper] > data[lower]) { temp = data[lower]; data[lower] = data[upper]; data[upper] = temp; } } } Paul I Lin

  22. Bubble Sort – Example 11-4(cont.) /* bubble sort */ sort(no, MAX); /* display sorted array */ for(i = 0; i < MAX; ++i) { printf("no[%d] = %u\n", i, no[i]); } puts("Enter a number for searching"); scanf("%d", &number); } void main() { int i, number, found; unsigned int j; for(i = 0; i < MAX; ++i) { no[i] = j = rand(); printf("Random number(%d) = %u\n", i,j); srand(i+2); } Paul I Lin

  23. Bubble Sort – Example 11-4(cont.) Running Results: Random number(0) = 16838 Random number(1) = 908 Random number(2) = 17747 Random number(3) = 1817 Random number(4) = 18655 Random number(5) = 2726 Random number(6) = 19564 Random number(7) = 3634 Random number(8) = 20472 Random number(9) = 4543 no[0] = 908 no[1] = 1817 no[2] = 2726 no[3] = 3634 no[4] = 4543 no[5] = 16838 no[6] = 17747 no[7] = 18655 no[8] = 19564 no[9] = 20472 Paul I Lin

  24. Searching Elements in Arrays • Determine whether an array contains a value that matches a certain key value. • The process of finding a particular element of an array is searching. • Type of searching: • Linear search – compares each element of the array with the search key • Brainy search – eliminates from consideration one half of the elements in a sorted array after each comparison. The worse case of searching is n times, where n is 2 to the power of n or 2n Examples: • An array of 1023 elements will take less then 10 comparisons using brainy search. 1023 < 210 • An array of 65536 elements will take less then 16 comparisons using brainy search. 65535 < 216 Paul I Lin

  25. Binary Search – Example 11-5 void sort(int data[], int size) { int upper, lower, temp; // Loop for counting the number of passes for(upper = 0; upper < size -1; upper++) { // Loop for comparison and exchange for(lower = upper + 1; lower < size; lower++) { if(data[upper] > data[lower]) { temp = data[lower]; data[lower] = data[upper]; data[upper] = temp; } } } /* bubblesort.c */ #include <math.h> #include <stdio.h> #define MAX 10 int no[MAX]; unsigned long int next = 1; /* rand(): return psedo-random integer from 0...32767 */ int rand(void) { next = next * 1103515245 + 12345; return (unsigned int) (next/65536) % 32768; } /* srand: set seed for rand() */ void srand(unsigned int seed) { next = seed; } Paul I Lin

  26. Binary Search – Example 11-5(cont.) void main() { int i, number, found; unsigned int j; for(i = 0; i < MAX; ++i) { no[i] = j = rand(); printf("Random number(%d) = %u\n", i,j); srand(i+2); } /* bubble sort */ sort(no, MAX); int binsearch(int x, int no[], int n) { int low, high, mid; low = 0; high = n-1; mid = (low + high) /2; while(low <= high && x != no[mid]) { if(x < no[mid]) high = mid -1; else low = mid + 1; mid = (low + high)/2; } if (x == no[mid]) return mid; /* found match */ else return -1; /* no match */ } Paul I Lin

  27. Binary Search – Example 11-5(cont.) /* display sorted array */ for(i = 0; i < MAX; ++i) { printf("no[%d] = %u\n", i, no[i]); } puts("Enter a number for searching"); scanf("%d", &number); /* binary search */ found = binsearch(number, no, MAX); if(found == -1) puts("Cant' find a match"); else printf("The number is in no[%d]\n", found); } Paul I Lin

  28. Binary Search – Example 11-5(cont.) Running Result Random number(0) = 16838 Random number(1) = 908 Random number(2) = 17747 Random number(3) = 1817 Random number(4) = 18655 Random number(5) = 2726 Random number(6) = 19564 Random number(7) = 3634 Random number(8) = 20472 Random number(9) = 4543 no[0] = 908 no[1] = 1817 no[2] = 2726 no[3] = 3634 no[4] = 4543 no[5] = 16838 no[6] = 17747 no[7] = 18655 no[8] = 19564 no[9] = 20472 Enter a number for searching 18655 The number is in no[7] Paul I Lin

  29. Multiple-subscripted arrays • A common use of multiple-subscripted arrays is to represent tables of values consisting of information arranged in rows and columns. • Table or arrays require two subscripts to identify a particular element. Example: m by n array means an array with m rows and n columns • To pass one row of a double-subscripted array to a function that receives a single-subscripted array, simply pass the name of the array followed by the subscript of that row. Paul I Lin

  30. Multiple-subscripted arrays(continue) Example 11-6: • Multiple subscripted arrays can have more than two subscripts • A multiple subscripted array can be initialized when it is defined as the same way as the 1-D example: static intmy_array[4][2][3] = { {{1, 2, 3}, { 4, 5, 6}}, {{7, 8, 9}, {10, 11, 12}}, {{13, 14, 15}, {16, 17, 18}}, {{19, 20, 21}, {22, 23, 24}} }; Paul I Lin

  31. Multiple-subscripted arrays(continue) /* Find the minimum grade of any student for the semester */ int minimum( const int grades[ ][ EXAMS ], int pupils, int tests ) { int i; /* student counter */ int j; /* exam counter */ int lowGrade = 100; /* initialize to highest possible grade */ /* loop through rows of grades */ for ( i = 0; i < pupils; i++ ) { /* loop through columns of grades */ for ( j = 0; j < tests; j++ ) { if ( grades[ i ][ j ] < lowGrade ) { lowGrade = grades[ i ][ j ]; } /* end if */ } /* end inner for */ } /* end outer for */ return lowGrade; /* return minimum grade */ } /* end function minimum */ Paul I Lin

  32. Multiple-subscripted arrays(continue) /*Determine the average grade for a particular student */ double average( const int setOfGrades[ ], int tests ) { int i; /* exam counter */ int total = 0; /* sum of test grades */ /* total all grades for one student */ for ( i = 0; i < tests; i++ ) { total += setOfGrades[ i ]; } /* end for */ return ( double ) total / tests; /* average */ } /* end function average */ Paul I Lin

  33. Programming Applications Example 11-7: Arithmetic Mean of N Numbers #define N 5 main() { float x[N] = {1.0, 2.0, 3.0, 4.0, 5.0}; float mean = 0.0; int i; for(i = 0; i < N; i++) mean += x[i]; mean /= N; printf(“mean = %f”, mean); } Paul I Lin

  34. Calculating the Sine using Series Approximation Example 11-8: A Sine function repeats itself every 2 radians. Using the sine series for an approximation of the sin(x) function: /* Program: sinesr.c - Approximation of the sin(x) function */ #define REG_TO_RAD 180.0/PI /* sinesr.c */ #include <math.h> #include <stdio.h> #define PI 3.14159 #define DEG_TO_RAD (180.0/PI) /* 57.29577951308232 */ Paul I Lin

  35. Calculating the Sine using Series(continue) #define x2(x) (x * x) /* Macro for x ^2 */ #define x3(x) (x * x * x) /* Macro for x^3 */ #define x5(x) (x*x*x*x*x) /* Macro for x^5 */ #define x7(x) (x*x*x*x*x*x*x) /* Macro for x^7 */ #define x9(x) (x*x*x*x*x*x*x*x*x) #define FAC3 (1*2*3) /* Factorial 3 */ #define FAC5 (1*2*3*4*5) /* Factorial 5 */ #define FAC7 (1*2*3*4*5*6*7) /* Factorial 7 */ #define FAC9 (1*2*3*4*5*6*7*8*9) void main(void) { double sinSER, sinLIB, error, x, n; printf("Deg Radians Sine Series Sin(x) Error\n"); Paul I Lin

  36. Calculating the Sine using Series(continue) printf("_________________________________________\n"); for(n = 0.0; n <= 90.0; n+=5.0) { x = n/DEG_TO_RAD; /*convert degree to radians*/ sinLIB = sin(x); sinSER = x - (x3(x)/FAC3)+ (x5(x)/FAC5)- (x7(x)/FAC7)+ (x9(x)/FAC9); error = sinSER - sinLIB; printf("%5.2lf %9.8lf %9.8lf %9.8lf %+.6e\n", n, x, sinLIB, sinSER, error); } printf("__________________________\n"); } Paul I Lin

  37. Calculating the Sine using Series(continue) Output: Deg Radians Sine Series Sin(x) Error __________________________________________________ 0.00 0.00000000 0.00000000 0.00000000 +0.000000e+000 5.00 0.08726639 0.08715567 0.08715567 +0.000000e+000 10.00 0.17453278 0.17364803 0.17364803 +1.110223e-016 15.00 0.26179917 0.25881883 0.25881883 +9.936496e-015 20.00 0.34906556 0.34201987 0.34201987 +2.347011e-013 25.00 0.43633194 0.42261793 0.42261793 +2.730927e-012 30.00 0.52359833 0.49999962 0.49999962 +2.027972e-011 35.00 0.61086472 0.57357601 0.57357601 +1.104591e-010 40.00 0.69813111 0.64278716 0.64278716 +4.795073e-010 45.00 0.78539750 0.70710631 0.70710631 +1.750303e-009 Paul I Lin

  38. Calculating the Sine using Series(continue) 50.00 0.87266389 0.76604397 0.76604397 +5.572419e-009 55.00 0.95993028 0.81915158 0.81915160 +1.588251e-008 60.00 1.04719667 0.86602496 0.86602500 +4.131496e-008 65.00 1.13446306 0.90630738 0.90630748 +9.953193e-008 70.00 1.22172944 0.93969227 0.93969249 +2.246074e-007 75.00 1.30899583 0.96592554 0.96592602 +4.790796e-007 80.00 1.39626222 0.98480755 0.98480852 +9.729044e-007 85.00 1.48352861 0.99619459 0.99619648 +1.892315e-006 90.00 1.57079500 1.00000000 1.00000354 +3.542551e-006 ___________________________________________________ Paul I Lin

  39. Summary • Determine Size of Arrays • Passing Arrays to Functions • Sorting/Searching Arrays • Multiple Subscripted Arrays • Programming Applications • Next – C Pointers Paul I Lin

  40. Questions? Answers lin@ipfw.edu Paul I Lin

More Related