one dimensional arrays review copying arrays arrays as function arguments sorting and searching techniques multidimensional arrays representation and realization initialization as function arguments ID: 784229
Download The PPT/PDF document "Chapter 7 - A closer look at Arrays" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Chapter 7 - A closer look at Arrays
one dimensional arrays (review)
copying arrays
arrays as function arguments
sorting and searching techniques
multi-dimensional arrays
representation and realization
initialization
as function arguments
Slide2One dimensional ArraysDefine with square brackets []type array_name [num_elements][] is an operator with the highest precedenceexample: char name[20]char[0] is the first element, char[19] is the last“sizeof” determines storage requirement of array (e.g. sizeof (name) = 20).the scope and privacy is the same as for scalars
Slide3Array bounds checkingC does not check that references to an array are valid, i.e. that the array subscript is between zero and num_elements-1advantages:faster program executiongreater reusability with function callsdisadvantages:easy to accidentally corrupt memoryreferring to array[num_elements] is a common programming error
Slide4Initialization of ArraysZero initialization rules same as for scalarsGeneric form for explicit initialization:type name[num+1]={val_0, val_1, ..., val_num}too many initial values generates errortoo few initial values results in the remainder of the array values set to zero, regardless of scope.if the array length is not specified, the number of initialization values determines the array length.
Slide5Copying arraysyou can not use the assignment operator (=) to copy an entire array. You must use a loop and element-by-element copying:#define SIZE 10...int i, y[SIZE], x[SIZE]={1,4,6,3,2,9,7,4,0,12};for (i=0;i<SIZE;i++) y[i]=x[i];
Slide6Arrays as function argumentsArrays are passed (simulated) call by reference. This means that:actually the address of the FIRST element in the array is given to the called functionthe called function can modify the contents of the original array in the calling function.Since there is no bounds checking, the length of arrays need not be specified in the called function.
Slide7Program 7.1 - bubble sort functionvoid bubble_sort(int num[], int count){ int temp, i, j; for(j=0;j<count-1;j++) for(i=j+1;i<count;i++) if(num
[i]>num[j]) temp=num[i], num[i]=num[j], num[j]=temp; return;}
Slide8Program 7.1 - main function (part 1)
/* new bubble sort program of an integer array */
#include <
stdio.h
>
int
main(void)
{
void
bubble_sort
(
int
[],
int
);
int
num
[100],
i
, count;
for(count=0;count<100;count++) {
printf
("Enter a number: ");
if (
scanf
("%d",&
num
[count])==EOF)
break;
}
Slide9Program 7.1 - main function (part 2) if (num[count]<=0) break; }// print array before we start to sort printf("\n\nThe unsorted array is:\n"); for(i=0;i<count;i++) printf("%c %d",i%10?' ':'\n',num[i]);// bubble_sort(num,count);
Slide10Program 7.1 - main function (part 3)//// finished sort high to low; print results printf("\n\nThe SORTED array is:\n"); for(i=0;i<count;i++) printf("%c %d",i%10?' ':'\n',num[i]); printf("\n\n"); return 0;}
Slide11Program 7.2 - array statisticsRead in an array of integers, find, and print the maximum, minimum, median, mean, and mode values.
Slide12Program 7.2 - specification
start
declare variables
prompt for input
read in an array of numbers, stop at EOF
sort the numbers from high to low
compute and print
max, min, median, mean, mode
stop
Slide13Program 7.2 - part 1/* program to calculate array statistics */#include <stdio.h>int main(void){ void bubble_sort(int[],int); int num[100], count, mean(int[],int), mode(int
[],int); for(count=0;count<100;count++) { printf("Enter a number (0 to exit): "); if (scanf("%d",&num[count])==EOF) break;
Slide14Program 7.2 - part 2 if (num[count]<=0) break; }bubble_sort(num,count); printf("Array maximum = %d \n",num[0]); printf("Array minimum = %d \n",num[count-1]); printf("Array median = %d \n",num[count/2]);
printf("Array mean = %d \n",mean(num,count)); printf("Array mode = %d \n",mode(num,count)); return 0;}
Slide15Program 7.2 - part 3int mean(int num[], int count){ int avg=0, i; for(i=0;i<count;avg+=num[i++]); return (avg/count);}
Slide16Program 7.2 - part 4int mode(int num[], int count){ int i=0, omode=0, nmode, otemp, ntemp; while (i<count-1) { ntemp
=num[i]; for(nmode=1;i<(count-1)&&ntemp==num[++i];nmode++); if (nmode>omode) { otemp=ntemp; omode=nmode; } }
printf(“frequency = %d \n”,omode); return
otemp
;
}
Slide17Array Searchingkey: is value present in array?if yes, return array locationif no, return “no match”search types:linear searchbinary search
Slide18Linear searchstart at first value and move up through array until value is found.takes an average of n/2 comparisons (if key is present)good method for small or unsorted arraysfor (i=0,j=-1;i<max_num;i++) if (array[i]==key) { j=i; break; }return j;
Slide19Binary searchmust have an ordered array (low-to-high or high-to-low)must first perform a sortcompare key to middle value (high-to-low).if key is the same, return resultif key is smaller, discard lower half of arrayif key is larger, discard upper half of arrayif array down to one value, return no match
Slide20Program 7.3 - Binary search functionint binary_search(int num[],int count, int key){ int low=0, high=count-1, middle; while (low<=high) { middle=(low+high)/2; if (key > num[middle]) high=middle-1;
else if (key < num[middle]) low=middle+1; else return middle; } return -1;}
Slide21Program 7.3 - main (part 1)/* new binary search program of an integer array */#include <stdio.h>int main(void){ void bubble_sort(int[],int); int binary_search(int[],int,int), num[100], i
, count, key, loc; for(count=0;count<100;count++) { printf("Enter a number (0 to exit): "); if (scanf("%d",&num[count])==EOF) break;
Slide22Program 7.3 - main (part 2) if (num[count]<=0) break; } for(i=0;i<count;i++) printf("%c %d",i%10?' ':'\n',num[i]); bubble_sort(num,count); for(
i=0;i<count;i++) printf("%c %d",i%10?' ':'\n',num[i]); printf("\n Enter a key: "); scanf("%d",&key); loc=binary_search(num,count,key);
Slide23Program 7.3 - main (part 3) if (loc==-1) printf("error: key was not found\n"); else printf("key found in position %d\n",loc); return 0;}
Slide24Multi-dimensional arraysMulti-dimensional arrays are natural for many situations:chess board (2-D)matrices (2-D)arrays of strings (2-D)scalar fields in space (3-D)vector fields in space (9-D)We will only worry about 2-D arrays here
Slide252-D Arraysgeneral definition:type array_name[num_rows][num_columns]you can visualize it as a 2-D grid with num_rows rows by num_columns columns.In memory, they are actually stored linearly, with the outermost subscript (the column) varying most rapidly.
Slide262-D Array - exampleConsider the array: int num[3][4]. The numbers are stored in memory like so:num[0][0] (first) num[1][2]num[0][1] num[1][3]num[0][2] num[2][0]num[0][3] num[2][1]num[1][0]
num[2][2]num[1][1] num[2][3] (last)
Slide27Accessing multi-dimensional arraysgiven our example: num[3][4], the usual way to reference the element in the second row and the third column is:num[1][2]NB: num[1,2] and num(1,2) are common errors!num[1] (without second subscript) references the entire second row (is a 1-D array)
Slide282-D array initializationExample:int num[3][4]={{1,2,3,4},{5,6,7},{9,10,11,12}};general rules:initial values are loaded by varying most rapidly the outer subscript and working inwardbraces enclose the entire initialization sequencebraces enclose each row of valuesif any values are missing from row data, the later column values are set to zero
Slide292-D array initialization - ctdif any rows are missing, the later rows are set to zerotoo many initial values is an errorif the number of columns is not specified, the number of rows is determined from the initial conditionsexample: we get three rows below:int num[][4]={{1,2,3,4},{5,6,7},{9,10,11,12}};
Slide30Program 7.4 - simple 2-D array test/* 2-D integer array */#include <stdio.h>int main(void){ int num[4][4]={{1,2,3,4},{5,6,7},{9,10,11,12}}, i, j; for (i=0;i<4;i++) for(j=0;j<4;j++) printf("array element [%d][%d]=%d\n",i,j,num[
i][j]); return 0;}
Slide31Multi-dimensional array argumentsshould have the same number of dimensions in the calling and called functionsthe number of elements in the inner most dimension is optional; all others must be specifiedlast statement is true for both the function prototype and the function header.
Slide32Example 2-D argumentsin calling function: in called function:int main (void) int test(int num[][4]){ { int test(int[][4]), y; int x; int num
[3][4]; ... ... return x; y=test(num); } ...