Download presentation
Presentation is loading. Please wait.
1
CNG 140 C Programming (Lecture set 8)
Spring Chapter 8 Arrays
2
Objectives: arrays Declaring Arrays Array Initialization
Arrays as Function Arguments Case Study: Computing Averages and Standard Deviations Two-Dimensional Arrays Common Programming and Compiler Errors CNG 140 C Programming 20062
3
Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in data type Also called a scalar variable Data structure (aggregate data type): data type with two main characteristics Its values can be decomposed into individual data elements, each of which is either atomic or another data structure It provides an access scheme for locating individual data elements within the data structure CNG 140 C Programming 20062
4
Introduction (continued)
CNG 140 C Programming 20062
5
Arrays One of the simplest data structures, called an array, is used to store and process a set of values, all of the same data type, that forms a logical group Arrays could be multi dimensional A one-dimensional array, also called a single-dimensional array and a single-subscript array, is a list of values of the same data type that is stored using a single group name CNG 140 C Programming 20062
6
One-Dimensional Arrays (example)
CNG 140 C Programming 20062
7
One-Dimensional Arrays (continued)
To create a one-dimensional array: required: name and size #define NUMELS 5 // size as constant symbol int grades[NUMELS]; // declaration with a name In C, the starting index value for all arrays is 0 Each item in an array is called an element or component of the array Any element can be accessed by giving the name of the array and the element’s position The position is the element’s index or subscript Each element is called an indexed variable or a subscripted variable CNG 140 C Programming 20062
8
One-Dimensional Arrays: int grades[5]
CNG 140 C Programming 20062
9
One-Dimensional Arrays (continued)
Subscripted variables can be used anywhere scalar variables are valid grades[0] = 98; grades[1] = grades[0] - 11; Any expression that evaluates an integer may be used as a subscript #define NUMELS 5 total = 0; /* initialize total to zero */ for (i = 0; i < NUMELS; i++) total = total + grades[i]; /* add a grade */ CNG 140 C Programming 20062
10
Input and Output of Array Values
Individual array elements can be assigned values using individual assignment statements or, interactively, using the scanf() function #define NUMELS 5 for(i = 0; i < NUMELS; i++) { printf("Enter a grade: "); scanf("%d", &grades[i]); } Be careful: C does not check the value of the index being used (called a bounds check) CNG 140 C Programming 20062
11
Input and Output of Array Values (continued)
Sample output: Enter a grade: 85 Enter a grade: 90 Enter a grade: 78 Enter a grade: 75 Enter a grade: 92 grades 0 is 85 grades 1 is 90 grades 2 is 78 grades 3 is 75 grades 4 is 92 CNG 140 C Programming 20062
12
Input and Output of Array Values (continued)
Statement is outside of the second for loop; total is displayed only once, after all values have been added CNG 140 C Programming 20062
13
Example Problem Write a function to find the index of the maximum and minimum numbers in an array. Write the main program which reads the size of an array and all the elements of the array. It shoul then call the previous function MaxMin to display the index and values of the maximum and minimum numbers CNG 140 C Programming 20062
14
Example Problem (Cont.)
void MaxMin(int array ar[100], numels, *I, *j) { int max, min, count; min=ar[0]; max=ar[0]; for(count = 0; count < numels; ++count) if (max < temp[count]) max = temp[count]; *i=count; } if (min > temp[count]) min = temp[count]; *j=count; return; CNG 140 C Programming 20062
15
Example Problem (Cont.)
#include <stdio.h> void MaxMin(int array ar[100], int, int *, int *) int main() { int ar[100], max, min; ………. MaxMin(ar,numels, &max, &min); printf("\nMax Element #%d = %d \nMin Element #%d = %d", max, ar[max], min, ar[min]); return 0; } CNG 140 C Programming 20062
16
Exercises 8.1.4 and 8.1.5 CNG 140 C Programming 20062
17
Array Initialization All global arrays are created once at compilation time. They retain their values during the execution All static arrays are created once at compilation time. All auto arrays have local scope, thus they are lost once the function declaring them exits Array elements can be assigned values in the declaration statements CNG 140 C Programming 20062
18
Array Initialization (cont.)
The individual elements of all global and static arrays (local or global) are, by default, set to 0 at compilation time The values within auto local arrays are undefined Examples of initializations: int grades[5] = {98, 87, 92, 79, 85}; double length[7] = {8.8, 6.4, 4.9, 11.2}; char codes[6] = {'s', 'a', 'm', 'p', 'l', e'}; char codes[] = {'s', 'a', 'm', 'p', 'l', 'e'}; char codes[] = "sample"; /* size is 7 */ CNG 140 C Programming 20062
19
Array Initialization (continued)
1 #define SIZE1 20 2 #define SIZE2 25 3 #define SIZE3 15 4 5 int gallons[SIZE1]; /* a global array */ 6 static int dist[SIZE2]; /* a static global array */ 7 8 int main() 9 { 10 int miles[SIZE3]; /* an auto local array */ 11 static int course[SIZE3]; /* static local array */ 12 . 13 . 14 return 0; 15 } CNG 140 C Programming 20062
20
Array Initialization (Strings)
The last character in a string is always assigned a NULL character \0 The NULL character, which is the escape sequence \0, is automatically appended to all strings by the C compiler. For example \0 is added as the last character to the following string: char codes[6] = {'s', 'a', 'm', 'p', 'l', e'}; CNG 140 C Programming 20062
21
Array Initialization (continued)
CNG 140 C Programming 20062
22
Array Initialization (Example program)
Assign values to an array and find the maximum CNG 140 C Programming 20062
23
Problem 8.2.2 Write a program that declares a string, say “This is CNG140 course” and prints the characters using “%c” and “%s” format specifications CNG 140 C Programming 20062
24
Problem Description: 8.2 Exercise 2a
#include <stdio.h> int main() { char strtest[22] = "This is CNG140 course"; int i; for ( i = 0; i <=21; i++ ) printf ( "%c", strtest[i] ); printf ( "%s", strtest ); /*For this the last char must be \0 */ return 0; } CNG 140 C Programming 20062
25
Exercise Input number of students, and their grades as an array, before finding the maximum, minimum and the average and print all… CNG 140 C Programming 20062
26
Arrays as Function Arguments
Individual array elements are passed to a function by including them as subscripted variables in the function call argument lists: Pass by value findMin(grades[2], grades[6]); When passing a complete array to a function, the called function receives access to the actual array, rather than a copy of the values in the array Pass by reference findMax(grades); CNG 140 C Programming 20062
27
Arrays as Function Arguments (continued)
Maximum array size is set to 5 Size can be omitted CNG 140 C Programming 20062
28
Arrays as Function Arguments (continued)
Array size in the function header better be omitted! CNG 140 C Programming 20062
29
Arrays as Function Arguments (continued)
CNG 140 C Programming 20062
30
Arrays as Function Arguments (a complete program)
CNG 140 C Programming 20062
31
Insertion sort-1 use a function called insert, designed to insert a value into a sorted sequence at the beginning of an array. Ex: 3, 8, 5 becomes 3, 5, 8 To perform insertion sort, start at the left end of the array and invoke insert to insert each element encountered into its correct position. Sorted: 3, 5, 8, unsorted: 1, 15, 4, 7, 6, 20, 11, 2 CNG 140 C Programming 20062
32
Insertion sort-2 /*Insertion sort: insert the the value in its place in the sorted part of the array */ insert(array a, int length, value) { int i = length - 1; while (i >= 0 && a[i] > value) a[i + 1] = a[i]; i = i - 1; } a[i + 1] := value; insertionSort(array a, int length) /* each time one value find its place in the sorted array */ for (int i = 0; i < length; i = i + 1) insert(a, i, a[i]); CNG 140 C Programming 20062
33
Case Study: Computing Averages and Standard Deviations
Two statistical functions are created to determine the average and standard deviation, respectively, of an array of numbers. Standard deviation is square root of the sum of the square of the differences between individual elements and the average divided by the number of elements. Sqrt(∑(x-avg)2/n) CNG 140 C Programming 20062
34
Requirements Specification
Need two functions Determine the average… Determine the standard deviation… Each function must accept the numbers as an array and return the calculated values to the calling function CNG 140 C Programming 20062
35
Analyze the Problem Determine the input items: list of integer numbers
Determine the desired outputs: (1) average, and (2) standard deviation List the algorithms relating the inputs and outputs: Average Function: Calculate the average by adding the grades and dividing by the # of the grades Standard Deviation Function: Subtract the average from each individual grade. Each number in the new set is called a deviation. Square each deviation found in Step 1. Add the squared deviations and divide the sum by the number of deviations. The square root of the number found in Step 3 is the standard deviation. CNG 140 C Programming 20062
36
Select an Overall Solution
Initialize an array of integers Call the average function Call the standard deviation function Display the returned value of the average function Display the returned value of the standard deviation function CNG 140 C Programming 20062
37
Write the main Function which calls functions findAvg and stdDev
CNG 140 C Programming 20062
38
Write the Functions (continued)
CNG 140 C Programming 20062
39
Test and Debug the Functions
Write a main() program unit to call the function and display the returned results (see Program 8.6) A test run using Program 8.6 produced the following display: The average of the numbers is 76.40 The standard deviation of the numbers is 13.15 Testing is not complete without verifying the calculation at the boundary points Checking the calculation with all of the same values, such as all 0s and all 100s Use five 0s and five 100s CNG 140 C Programming 20062
40
Two-Dimensional Arrays
CNG 140 C Programming 20062
41
Two-Dimensional Arrays (continued)
CNG 140 C Programming 20062
42
Two-Dimensional Array Declaration
A two-dimensional array, or table, consists of both rows and columns of elements int val[3][4]; CNG 140 C Programming 20062
43
Two-Dimensional Arrays (continued)
Initialization: #define NUMROWS 3 #define NUMCOLS 4 int val[NUMROWS][NUMCOLS] = { {8,16,9,52}, {3,15,27,6}, {14,25,2,10} }; The inner braces can be omitted: int val[NUMROWS][NUMCOLS] = {8,16,9,52,3,15,27, 6,14,25,2,10}; Initialization is done in row order CNG 140 C Programming 20062
44
Two-Dimensional Arrays (continued)
CNG 140 C Programming 20062
45
Printing Two-Dimensional Arrays
CNG 140 C Programming 20062
46
Two-Dimensional Arrays: printing methods
Print using individual elements Print using for loops CNG 140 C Programming 20062
47
Two-Dimensional Arrays (continued)
The display produced by Program 8.7 is Display of val array by explicit element Display of val array using a nested for loop CNG 140 C Programming 20062
48
Two-Dimensional Arrays (continued)
Multiply each element of the array by 10 and print CNG 140 C Programming 20062
49
Two-Dimensional Arrays: all in main function
CNG 140 C Programming 20062
50
Two-Dimensional Arrays: call a function to print
Row size can be omitted CNG 140 C Programming 20062
51
Two-Dimensional Arrays: offset computation
Column size is used to locate (compute the address of) the individual elements in the memory CNG 140 C Programming 20062
52
Internal Array Element Location Algorithm
Each element in an array is reached by adding an offset to the starting address of the array Address element i = starting array address + offset For single-dimensional arrays: Offset = i * the size of an individual element For two-dimensional arrays: Offset = column index value * the size of an individual element + row index value * # of bytes in a complete row # of bytes in a complete row = maximum column specification * the size of an individual element CNG 140 C Programming 20062
53
Internal Array Element Location Algorithm (continued)
CNG 140 C Programming 20062
54
Larger Dimensional Arrays
A three-dimensional array can be viewed as a book of data tables (the third subscript is called the rank) int response[4][10][6]; A four-dimensional array can be represented as a shelf of books where the fourth dimension is used to declare a desired book on the shelf A five-dimensional array can be viewed as a bookcase filled with books where the fifth dimension refers to a selected shelf in the bookcase Arrays of three, four, five, six, or more dimensions can be viewed as mathematical n-tuples CNG 140 C Programming 20062
55
Common Programming Errors
Forgetting to declare the array Using a subscript that references a nonexistent array element Not using a large enough conditional value in a for loop counter to cycle through all the array elements Forgetting to initialize the array CNG 140 C Programming 20062
56
Common Compiler Errors
CNG 140 C Programming 20062
57
Summary A single-dimensional array is a data structure that can store a list of values of the same data type Elements are stored in contiguous locations Referenced using the array name and a subscript Single-dimensional arrays may be initialized when they are declared Single-dimensional arrays are passed to a function by passing the name of the array as an argument CNG 140 C Programming 20062
58
Summary (continued) A two-dimensional array is declared by listing both a row and a column size with the data type and name of the array Two-dimensional arrays may be initialized when they are declared Two-dimensional arrays are passed to a function by passing the name of the array as an argument CNG 140 C Programming 20062
59
Linear Search #include <stdio.h> #define TRUE 1 #define FALSE 0
#define NUMEL 10 int linearSearch (int [], int, int); CNG 140 C Programming 20062
60
Linear Search: main() int main() {
int nums[NUMEL] = {5,10,22,32,45,67,73,98,99,101}; int item, location; printf("Enter the item you are searching for: "); scanf("%d", &item); location = linearSearch(nums, NUMEL, item); if (location > -1) printf("The item was found at index location %d\n", location); else printf("The item was not found in the list\n"); return 0; } CNG 140 C Programming 20062
61
Linear Search: linearSearch()
int linearSearch(int list[], int size, int key) /* this function returns the location of key in the list */ /* a -1 is returned if the value is not found */ { int index, found, i; index = -1; found = FALSE; i = 0; while (i < size && !found) if (list[i] == key) found = TRUE; index = i; } i++; /* move to next item in the list */ return (index); CNG 140 C Programming 20062
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.