Presentation is loading. Please wait.

Presentation is loading. Please wait.

C Arrays (2) (Chapter 6) ECET 264.

Similar presentations


Presentation on theme: "C Arrays (2) (Chapter 6) ECET 264."— Presentation transcript:

1 C Arrays (2) (Chapter 6) ECET 264

2 Topics Array applications Total Average
double average(const int setOfGrades[ ], int tests) Printing : void printArray(const int grades[][EXAMS], int pupils, int tests) Min int minimum(const int grades[][EXAMS], int pupils, int tests) Max int maximum(const int grades[][EXAMS], int pupils, int tests) Sorting Searching

3 Topics Total total = 0; for (j =0; j<SIZE; j++) {
total += answer[j]; }

4 Topics Total total = 0; for (row=0;row < STUDENTS; row++)
for (column=0; column < EXAMS ; column++) total += grades [row] [column];

5 Outline (1 of 2 ) fig06_21.c array1 is initialized with both rows full
array2 and array3 are initialized only partially

6 Outline fig06_21.c (2 of 2 )

7 Outline fig06_22.c (1 of 6 ) Each row in the array corresponds to a single student’s set of grades

8 Outline fig06_22.c (2 of 6 ) average function is passed a row of the array

9 Outline fig06_22.c (3 of 6 )

10 Outline fig06_22.c (4 of 6 )

11 Outline fig06_22.c (5 of 6 )

12 Outline fig06_22.c (6 of 6 )

13 Sorting Arrays Sorting data Bubble sort (sinking sort) Example:
Important computing application Virtually every organization must sort some data Bubble sort (sinking sort) Several passes through the array Successive pairs of elements are compared If increasing order (or identical ), no change If decreasing order, elements exchanged Repeat Example: original: pass 1: pass 2: Small elements "bubble" to the top

14 Outline fig06_15.c (1 of 2 )

15 Outline If any two array elements are out of order, the function swaps them fig06_15.c (2 of 2 )

16 Function for Bubble sorting void bubbleSort (int a[ ]) (figure 6.16)
/* function that sorts an array with bubble sort algorithm */ void bubbleSort( int a[] ) { int pass; /* pass counter */ int j; /* comparison counter */ int hold; /* temporary location used to swap elements */ /* loop to control number of passes */ for ( pass = 1; pass < SIZE; pass++ ) { /* loop to control number of comparisons per pass */ for ( j = 0; j < SIZE - 1; j++ ) { /* swap elements if out of order */ if ( a[ j ] > a[ j + 1 ] ) { hold = a[ j ]; a[ j ] = a[ j + 1 ]; a[ j + 1 ] = hold; } /* end if */ } /* end inner for */ } /* end outer for */ } /* end function bubbleSort */

17 Searching Arrays Search an array for a key value
Linear search (Figure 6.18) Simple Compare each element of array with key value Useful for small and unsorted arrays Binary search (Figure 6.19) For sorted arrays only Very fast

18 Outline fig06_18.c (1 of 3 )

19 Outline fig06_18.c (2 of 3 )

20 Outline Linear search algorithm searches through every element in the array until a match is found fig06_18.c (3 of 3 )


Download ppt "C Arrays (2) (Chapter 6) ECET 264."

Similar presentations


Ads by Google