Download presentation
Presentation is loading. Please wait.
1
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 1
2
One dimensional Arrays
Define with square brackets [] type array_name [num_elements] [] is an operator with the highest precedence example: 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
3
Array bounds checking C does not check that references to an array are valid, i.e. that the array subscript is between zero and num_elements-1 advantages: faster program execution greater reusability with function calls disadvantages: easy to accidentally corrupt memory referring to array[num_elements] is a common programming error
4
Initialization of Arrays
Zero initialization rules same as for scalars Generic form for explicit initialization: type name[num+1]={val_0, val_1, ..., val_num} too many initial values generates error too 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.
5
Copying arrays you 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];
6
Arrays as function arguments
Arrays are passed (simulated) call by reference. This means that: actually the address of the FIRST element in the array is given to the called function the 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.
7
Program 7.1 - bubble sort function
void 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; }
8
Program 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; } 5
9
Program 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);
10
Program 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; }
11
Program 7.2 - array statistics
Read in an array of integers, find, and print the maximum, minimum, median, mean, and mode values.
12
Program 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 5
13
Program 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;
14
Program 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;
15
Program 7.2 - part 3 int mean(int num[], int count) { int avg=0, i;
for(i=0;i<count;avg+=num[i++]); return (avg/count); }
16
Program 7.2 - part 4 int 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;
17
Array Searching key: is value present in array? search types:
if yes, return array location if no, return “no match” search types: linear search binary search
18
Linear search start 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 arrays for (i=0,j=-1;i<max_num;i++) if (array[i]==key) { j=i; break; } return j;
19
Binary search must have an ordered array (low-to-high or high-to-low)
must first perform a sort compare key to middle value (high-to-low). if key is the same, return result if key is smaller, discard lower half of array if key is larger, discard upper half of array if array down to one value, return no match
20
Program 7.3 - Binary search function
int 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;
21
Program 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;
22
Program 7.3 - main (part 2) break; } for(i=0;i<count;i++)
if (num[count]<=0) break; } for(i=0;i<count;i++) printf("%c %d",i%10?' ':'\n',num[i]); bubble_sort(num,count); printf("\n Enter a key: "); scanf("%d",&key); loc=binary_search(num,count,key);
23
Program main (part 3) if (loc==-1) printf("error: key was not found\n"); else printf("key found in position %d\n",loc); return 0; }
24
Multi-dimensional arrays
Multi-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
25
2-D Arrays general 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.
26
2-D Array - example Consider 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)
27
Accessing multi-dimensional arrays
given 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)
28
2-D array initialization
Example: 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 inward braces enclose the entire initialization sequence braces enclose each row of values if any values are missing from row data, the later column values are set to zero
29
2-D array initialization - ctd
if any rows are missing, the later rows are set to zero too many initial values is an error if the number of columns is not specified, the number of rows is determined from the initial conditions example: we get three rows below: int num[][4]={{1,2,3,4},{5,6,7},{9,10,11,12}};
30
Program 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; }
31
Multi-dimensional array arguments
should have the same number of dimensions in the calling and called functions the number of elements in the inner most dimension is optional; all others must be specified last statement is true for both the function prototype and the function header.
32
Example 2-D arguments in 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); } ...
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.