Problem Solving and Program Design in C Chap. 7 Arrays Chow-Sing Lin.

Slides:



Advertisements
Similar presentations
Numeric Types & Ranges. ASCII Integral Type Numerical Inaccuracies Representational error – Round-off error – Caused by coding a real number as a finite.
Advertisements

Introduction to C Programming
One Dimensional Arrays
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
Enumerated Types 4 Besides the built-in types, ANSI C allows the definition of user-defined enumerated types –To define a user-define type, you must give.
Topic 9 – Introduction To Arrays. CISC105 – Topic 9 Introduction to Data Structures Thus far, we have seen “simple” data types. These refers to a single.
5 5 Arrays. OBJECTIVES In this lecture we will learn:  Case switch  To use the array data structure to represent a set of related data items.  To declare.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
1 TDBA66, VT-04, Lecture Ch7 One dimensional Arrays A data structure (vector) with many elements of the same type A common name where individual elements.
1 CS 201 Array Debzani Deb. 2 Having trouble linking math.h? Link with the following option gcc –lm –o test test.o.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 ICS103 Programming in C Lecture 12: Arrays I. 2 Outline Motivation for One-dimensional Arrays What is a One-dimensional Array? Declaring One-dimensional.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 Pearson Education, Inc. All rights reserved Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
 2006 Pearson Education, Inc. All rights reserved Arrays.
chap8 Chapter 8 Arrays (Hanly) chap8 2 Data Structure Simple data types use a simple memory to store a variable. Data Structure: a.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 7 Simple Date Types J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University.
Chapter 8 Arrays and Strings
Chapter 8 Arrays Part II J. H. Wang ( 王正豪 ), Ph. D. Assistant Professor Dept. Computer Science and Information Engineering National Taipei University of.
Problem Solving and Program Design in C (5th Edition) by Jeri R. Hanly and Elliot B. Koffman CP 202 Chapter
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
 Pearson Education, Inc. All rights reserved Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Chapter 8 Arrays Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
Arrays Why we need data structure? Simple data types use a single memory cell to store a variable. Sometimes (for example scores of a class) it is more.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
Computer Programming Lecture 8 Arrays. 2 switch-statement Example (3) If use press left arrowIf use press right arrow If use press up arrow If use press.
Chapter 8 Arrays Dr. Jiung-yao Huang Dept. Comm. Eng. Nat. Chung Cheng Univ. TA: 鄭筱親 陳昱豪.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Unit 6 Data Types and Arrays. Key Concepts Explicit and automatic conversion ASCII Enumerated types Function parameters Arrays Loops and arrays Passing.
 2005 Pearson Education, Inc. All rights reserved Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
 2006 Pearson Education, Inc. All rights reserved Arrays and Vectors.
Problem Solving and Program Design in C Chap. 6 Pointers and Modular Programming Chow-Sing Lin.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Objectives You should be able to describe: One-Dimensional Arrays
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
ARRAYS.
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
Arrays and Records.
7 Arrays.
EKT150 : Computer Programming
7 Arrays.
Presentation transcript:

Problem Solving and Program Design in C Chap. 7 Arrays Chow-Sing Lin

Declaring and Referencing Arrays Arrays – A collection of data items of the same type Array elements – An array is a collections of two or more adjacent memory cells To set up an array in memory – We must declare both the name of the array and the number of cells associated with it Dr. Chow-Sing Lin2Arrays - CH8

Declaring and Referencing Arrays (Cont.) The declaration double x[8]; – Instructs the compiler to associate eight memory cells with name x – These memory cells will be adjacent to each other in memory – Each element of array x may contain a single type double value A total of eight such numbers may be stored and referenced using the array name x Dr. Chow-Sing Lin3Arrays - CH8

Declaring and Referencing Arrays (Cont.) Subscripted variable – A variable followed by a subscript in brackets, designating an array element x[0] – Read as x sub zero – x[1] the next element double x[8] – x[7] the last element Dr. Chow-Sing LinArrays - CH84

Declaring and Referencing Arrays (Cont.) Array subscript – The integer enclosed in brackets Value in the range from zero to one less than the number of memory cells in the array (0.. n-1) – A value of expression enclosed in brackets after the array name Specifying which array element to access Dr. Chow-Sing LinArrays - CH85

Declaring and Referencing Arrays (Cont.) Example 7.1 – Let x be the array shown in Figure. 8.1 – x[1] is the second array element – X[7] is the last element Dr. Chow-Sing LinArrays - CH86

Declaring and Referencing Arrays (Cont.) Dr. Chow-Sing LinArrays - CH87 StatementExplanation printf (“%.1f”, x[0]);Displays the value of x[0], which is 16.0 x[3] = 25.0;Stores the value 25.0 in x[3] sum = x[0] + x[1];Stores the sum of x[0] and x[1], which is 28.0 in the variable sum sum += x[2];Adds x[2] to sum. The new sum is 34.0 x[3] += 1.0;Adds 1.0 to x[3]. The new x[3] is 26.0 x[2] = x[0] + x[1];Stores the sum of x[0] and x[1] in x[2]. The new x[2] is x[0]x[1]x[2]x[3]x[4]x[5]x[6]x[7]

Declaring and Referencing Arrays (Cont.) Array declaration Dr. Chow-Sing LinArrays - CH88 Element-type aname [size];/* uninitialized */ element-type aname [size] = {initialization list};/*initialized */ SYNTAX #define A_SIZE 5 ‧‧‧ double a[A_SIZE]; char vowels [ ] = {‘A’, ‘E’, ‘I’, ‘O’, ‘U’}; Example

Example We declare two arrays for a student records program We assume that NUM_STUDENTS has already appeared in a #define directive Dr. Chow-Sing LinArrays - CH89 intid [NUM_STUDENTS]; doublegpa [NUM_STUDENTS]; #defineNUM_STUDENTS 50

Example (Cont.) The array id and gpa each have 50 elements Each element of array id can be used to store an integer value Each element of array gpa can be used to store a value of type double If you use these declarations in a problem to assess the range and distribution of grade point average – Store the first student’s id in id[0] – Store the same student’s gpa in gpa[0] Dr. Chow-Sing LinArrays - CH810

Example (Cont.) Parallel arrays – Two or more arrays with the same number of elements used for storing related information about a collection of data objects Dr. Chow-Sing LinArrays - CH811

Arrays Initialization We can initialize a simple variable when we declare it : int sum = 0; We can also initialize an array in its declaration We can omit the size of an array that is being fully initialized – Since the size can be deduced from the initialization list Dr. Chow-Sing LinArrays - CH812

Arrays Initialization (Cont.) We initialize a 25-element array with the prime numbers less than 100 Dr. Chow-Sing LinArrays - CH813 int prime _lt_100[ ] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97};

Exercises Declare one array for storing the square roots of the integers from 0 through 10 and a second array for storing the cubes of the same integer. Dr. Chow-Sing LinArrays - CH814 doublesq_root [11]; intcube [11]; Answers

Array Subscripts Use any expression of type int as an array subscript Create a valid reference – The value of subscript must lie between 0 and one less than the declared size of the array Dr. Chow-Sing LinArrays - CH815 aname [subscript] SYNTAX b [i + 1] Example

Example 7.4 Dr. Chow-Sing LinArrays - CH816 StatementExplanation i = 5; printf (“%d %.1f”, 4, x[4]);Displays 4 and 2.5 (value of x[4]) printf (“%d %.1f”, i, x[i]);Displays 5 and 12.0 (value of x[5]) printf (“%.1f”, x[i] + 1);Displays 13.0 (value of x[5] plus 1) printf (“%.1f”, x[i] + i);Displays 17.0 (value of x[5] plus 5) printf (“%.1f”, x[i + 1]);Displays 14.0 (value of x[6]) printf (“%.1f”, x[i + i]);Invalid. Attempt to display x[10] printf (“%.1f”, x[2*i]);Invalid. Attempt to display x[10]

Example 7.4 (Cont.) Dr. Chow-Sing LinArrays - CH817 StatementExplanation printf (“%.1f”, x[2 * i - 3]);Displays (value of x[7]) printf (“%.1f”, x[(int)x[4]]);Displays 6.0 (value of x[2]) printf (“%.1f”, x[i++]);Displays 12.0 (value of x[5]); then assigns 6 to i printf (“%.1f”, x[--i]);Displays 5(6 – 1) to i and then displays 12.0 (value of x[5]) x[i – 1] = x[i];Assigns 12.0 (value of x[5]) to x[4] x[i] = x[i + 1];Assigns 14.0 (value of x[6]) to x[5] x[i] – 1 = x[i]Illegal assignment statement

Exercises for Section 72 Show the contents of array x after executing the valid statements in Table 7.2 Dr. Chow-Sing LinArrays - CH818 Before : After : x[0]x[1]x[2]x[3]x[4]x[5]x[6]x[7]

Using for Loops for Sequential Access Use an indexed for loop – Counting loop Loop control variable runs from zero to one less than the array size Using the loop counter as an array index (subscript) gives access to each array element in turn Dr. Chow-Sing LinArrays - CH819

Example 7.5 The array square will be used to store the squares of the integers 0 through 10 – square[0] is 0, square[10] is 100 – We assume that the name SIZE has been defined to be 11 int square[SIZE], i; – The for loop for (i = 0; i< SIZE; ++i) square[i] = i * i; – Initializes this array Dr. Chow-Sing LinArrays - CH x[0]x[1]x[2]x[3]x[4]x[5]x[6]x[7]X[8]X[9]X[10]

Statistical Computations Using Arrays One common use of arrays is for storage of a collection of related data values Once the values are stored, perform some simple statistical computations Figure 8.3 (Book Page 411) Program to Print a Table of Differences Dr. Chow-Sing LinArrays - CH821

Statistical Computations Using Arrays (Cont.) Dr. Chow-Sing LinArrays - CH822 ①

Dr. Chow-Sing LinArrays - CH823 ② ③

Statistical Computations Using Arrays (Cont.) First loop – Stores one input value into each element of array x The first item is placed in x[0] The next in x[1], and so on – The call to scanf is repeated for each value of i from 0 to 7 Second loop – Accumulates (in sum) the sum of all value stored in the array – Accumulates (in sum_sqr) the sum of the squares of all element values Dr. Chow-Sing LinArrays - CH824

Statistical Computations Using Arrays (Cont.) Second loop (Cont.) – This loop implements the formulas Third loop – Displays a table – Each line of the table displays an array subscript an array element the different between that element x[i] - mean Dr. Chow-Sing LinArrays - CH825

Statistical Computations Using Arrays (Cont.) Partial trace of computing for loop Dr. Chow-Sing LinArrays - CH826 Statementix[i]sumsum_sqrEffect sum = 0;0.0Initializes sum sum_sqr = 0;0.0Initializes sum_sqr for (i = 0;016.0Initializes i to 0 i < MAX_ITEM;Which is less than 8 ‧‧‧ sum += x[i];16.0Adds x[0] to sum sum_sqr += x[i] * x[i];256.0Adds to sum_sqr

Statistical Computations Using Arrays (Cont.) Dr. Chow-Sing LinArrays - CH827 Statementix[i]sumsum_sqrEffect increment and test i < 8 is true sum += x[i];28.0Adds x[1] to sum sum_sqr += x[i] * x[i];400.0Adds to sum_sqr increment and test i26.02 < 8 is true sum += x[i];34.0Adds x[2] to sum sum_sqr += x[i] * x[i];436.0Adds 36.0 to sum_sqr

Statistical Computations Using Arrays (Cont.) Standard deviation – Data is a measure of the spread of the data values around the mean – A small standard deviation indicates that the data values are all relatively close to the average value Dr. Chow-Sing LinArrays - CH828

Statistical Computations Using Arrays (Cont.) Standard deviation (Cont.) – For MAX_ITEM data items If we assume that x is an array Lowest subscript is 0 The standard deviation formula : st_dev = sqrt (sum_sqr / MAX_ITEM mean * mean); Dr. Chow-Sing LinArrays - CH829 Standard deviation

Using Array Elements as Function Arguments Use array element x[i] as an input argument to function printf When i is 3, the value of x[3] or 8.0 is passed to printf and displayed Dr. Chow-Sing LinArrays - CH830

Using Array Elements as Function Arguments (Cont.) The call scanf(“%lf”, &x[i]); – Use array element x[i] as an output argument of scanf – When i is 4 The address of array element x[4] is passed to scanf scanf stores the next value scanned (2.5) in element x[4] Dr. Chow-Sing LinArrays - CH831

Example 7.6 The function prototype below shows one type double input parameter (arg_1) and two type double * output parameters (arg2_p and arg3_p) If p, q, and r are declared as type double variables in the calling module – Passes the value of p to function do_it – Returns the function results to variables q and r Dr. Chow-Sing LinArrays - CH832 void do_it (double arg_1, double *arg2_p, double *arg3_p); do_it (p, &q, &r);

Example 8.9 (Cont.) If x is declared as an array of type double elements in the calling module Array element x[0] is an input argument Array element x[1] and x[2] are output arguments In function do_it, use statement to return value to the calling module Dr. Chow-Sing LinArrays - CH833 do_it (x[0], &x[1], &x[2]); *arg2_p = … *arg3_p = …

Dr. Chow-Sing LinArrays - CH834

Exercises for Section 7.4 Write a statement that assigns to see_len the length of a line segment from x i y i to x i+1 y i+1 using the formula Dr. Chow-Sing LinArrays - CH835 seg_len = sqrt(pow(x[i + 1] – x[i], 2) + pow(y[I + 1] – y[i], 2)); Answers

Array Arguments Besides passing individual array elements to functions, we can write functions that have arrays as arguments. Formal array parameter – Use array name, representing the address of initial array address, as formal parameter. – In the function body Use subscripts with the formal parameter to access the array’s elements – The function manipulates the original array An assignment to one of the array elements changes the contents of the original array. Dr. Chow-Sing LinArrays - CH836

Example 7.7 Figure shows a function that stores the same value (in_value) in all elements of the array corresponding to its formal array parameter list Dr. Chow-Sing LinArrays - CH837 Stores in_value in element i of its actual array argument Argument declaration does not indicate how many elements are in lists

Argument Correspondence for Array Parameters To call function fill_array – You must specify The actual array argument The number of array elements The value to be stored in the array – If y is array with ten type int elements The function call Stores the value of num in the ten elements of array y Dr. Chow-Sing LinArrays - CH838 fill_array(y, 10, num);

Argument Correspondence for Array Parameters (Cont.) To call function fill_array (Cont.) – If x is a five-element array of type int values – The statement Cause function fill_array to store 1 in all elements of array x Dr. Chow-Sing LinArrays - CH839 fill_array(x, 5, 1);

Argument Correspondence for Array Parameters (Cont.) Data areas before return from fill_array (x, 5, 1); Dr. Chow-Sing LinArrays - CH840

Argument Correspondence for Array Parameters (Cont.) C stores the address of the type int variable x[0] in list – In fact, the following call is exactly like the call above. For readability – When you call a function that processes the list the array represents, use the name of an array (with no subscript) Dr. Chow-Sing LinArrays - CH841 fill_array(&x[0], 5, 1);

Argument Correspondence for Array Parameters (Cont.) Use of *list instead of list[ ] in a formal parameter list – In the declaration for function fill_array We can use either parameter declaration : Dr. Chow-Sing LinArrays - CH842 int list[ ] int *list

Arrays as Input Arguments Array is only an input to the function and that the function does not intend to modify the array This qualifier, const, allows the compiler to mark as an error any attempt to change an array element within the function Dr. Chow-Sing LinArrays - CH843

Arrays as Input Arguments (Cont.) Array input Parameter Dr. Chow-Sing LinArrays - CH844 const element-type array-name[ ] or const element-type *array-name SYNTAX int get_min_sub (const double data[], /*input-array of numbers */ intdata_size) /*input-number of elements */ { int i, small_sub; /*subscript of smallest value so far */ small_sub = 0; /*Assume first element is smallest */ for (i = 1; i < data_size; ++i ) if (data[i] < data[small_sub]) small_sub = i; return (small_sub); } Example

Example 7.8 Function get_max in Figure can be called to find the largest value in an array Dr. Chow-Sing LinArrays - CH845 An array input parameter

Example 7.5 (Cont.) If x is a five-element array of type int values – The statement causes function get_max to search array x for its largest element – Value is returned and stored in x_large Dr. Chow-Sing LinArrays - CH846 x_large = get_max(x, 5);

Returning an Array Result Use an output parameter to send the result array back to the calling module A function returning an array result depends on its caller to provide an array variable into which the result can be stored Dr. Chow-Sing LinArrays - CH847

Example 7.9 Function add_arrays adds two arrays Dr. Chow-Sing LinArrays - CH848 Strictly input parameter

Example 7.9 (Cont.) The sum of arrays ar1 and ar2 is defined as arsum such that arsum[i] is equal to ar1[i] + ar2[i] for each subscript i The last parameter, n, specifies how many corresponding elements are summed The formal parameter list declaration Dr. Chow-Sing LinArrays - CH849 const double ar1[ ], const double ar2[ ], double arsum[ ], int n

Example 7.9 (Cont.) If a calling function has declared three five- ele3ment arrays x, y, and x_plus_y with data – The call add_arrays(x, y, x_plus_y, 5); Dr. Chow-Sing LinArrays - CH850

Example 7.9 (Cont.) Dr. Chow-Sing LinArrays - CH851

Example 7.9 (Cont.) After execution of the function – x_plus_y[0] will contain the sum of x[0] and y[0], or 3.5 – x_plus_y[1] will contain the sum of x[1] and y[1], or 6.7 Input argument arrays x and y will be unchanged Output argument arrays x_plus_y will have new contens Dr. Chow-Sing Lin Arrays - CH x_plus_y after call to add_arrays

Partially Filled Arrays A program will need to process many lists of similar data – Lists may not all be the same length! In order to reuse an array for processing more than one data set – Declares an array large enough to hold the largest data set anticipated Dr. Chow-Sing LinArrays - CH853

Example 7.10 Function fill_to_sentinel is to fill a type double array with data, until the designated sentinel value is encountered in the input data Dr. Chow-Sing LinArrays - CH854

Example 7.10 (Cont.) Use an array that may be only partially filled (such as db1_arr) – We must deal with two array sizes Array’s declared size – Input parameter dbl_max Size counting only the elements in use – Output parameter dbl_sizep Dr. Chow-Sing LinArrays - CH855

Fig 7.11 Dr. Chow-Sing LinArrays - CH856

Fig 7.12 Dr. Chow-Sing LinArrays - CH857 Output argument Address-of operator & is applied

Stacks A stack is a data structure in which only the top element can be accessed Popping the stack – Remove the top element of a stack Pushing it onto the stack – Insert a new element at the top of stack Dr. Chow-Sing LinArrays - CH858 C C How do we access the symbol “+” ? C C C C

Stacks (Cont.) Dr. Chow-Sing LinArrays - CH859

Stacks (Cont.) Array s stores a stack of up to STACK_SIZE characters s_top stores the subscript of the element at the top of the stack – Giving s_top an initial value of -1, ensures the first item pushed onto the stack will be stored in the stack element s[0] Dr. Chow-Sing LinArrays - CH860 char s[STACK_SIZE];/* a stack of characters */ int s_top = -1; /* stack s is empty */

Stacks (Cont.) The last character pushed (C) is at the top of the stack, array element s[2] Dr. Chow-Sing LinArrays - CH861 push (s, ‘2’, &s_top, STACK_SIZE); push (s, ‘+’, &s_top, STACK_SIZE); push (s, ‘c’, &s_top, STACK_SIZE);

Searching and Sorting an Array Searching an array to determine the location of a particular value Sorting an array to rearrange the array elements in numerical order Dr. Chow-Sing LinArrays - CH862

Array Search Linear search – In order to search an array We need to know the array element value we are seeking Search target – Perform the search Examining in turn each array element using a loop Testing whether the element matches the target – When the target value is found, search loop should be exited Dr. Chow-Sing LinArrays - CH863

Array Search (Cont.) Algorithm 1. Assume the target has not been found. 2. Start with the initial array element. 3. repeat while the target is not found and there are more array elements. 4.if the current element matches the target 5. Set a flag to indicate that the target has been found. 6. Advance to the next array element. 7.if the target was found 8.Return the target index as the search result. else 9.Return -1 as search result. Dr. Chow-Sing LinArrays - CH864

Dr. Chow-Sing LinArrays - CH865 Figure 7.14 Function That Searches for a Target Value in an Array

Sorting an Array Selection sort – To perform a selection sort of an array with n elements Subscripts 0 through n-1 – We locate the smallest element in the array – Switch the smallest element with the element at subscript 0 Placing the smallest element in the first position Dr. Chow-Sing LinArrays - CH866

Sorting an Array (Cont.) Selection sort (Cont.) – We locate the smallest element remaining in subarray with subscript 1 through n-1 and switch it with the element at subscript 1 Placing the second smallest element in the second position – And so on …………. Dr. Chow-Sing LinArrays - CH867

Sorting an Array (Cont.) Algorithm for Selection Sort 1.for each value of fill from 0 to n-2 2. Find index_of_min, the index of the smallest element in the unsorted subarray list[fill] through list[n-1]. 3 if fill is not the position of the smallest element (index_of_min) 4. Exchange the smallest element with the one at position fill. Dr. Chow-Sing LinArrays - CH868

Dr. Chow-Sing LinArrays - CH869 Figure 8.16 Trace of Selection Sort

Dr. Chow-Sing LinArrays - CH870 Figure 7.16 Function select_sort

Enumerated Types Enumerated type – Allows associate a numeric code with each category by creating an enumerated type that has its own list of meaningful values – A data type whose list of values is specified by the programmer in a type declaration typedef Dr. Chow-Sing LinSimple Data Types - CH771

Enumerated Types (Cont.) For example, the enumerated type expense_t has eight possible values : Dr. Chow-Sing LinSimple Data Types - CH772 typedef enum { entertainment, rent, utilities, food, clothing, automobile, insurance, miscellaneous } expense_t;

Enumerated Types (Cont.) Declaration of variable expense_kind : – Defining type expense_t as shown cause the enumeration constant entertainment to be represented as 0 constant rent to be represented as integer 1 utilities as 2, and so on Dr. Chow-Sing LinSimple Data Types - CH773 expense_t expense_kind;

Enumerated Types (Cont.) For types day_t, the following relations are true – sunday < monday – wednesday != friday – tuesday >= sunday Dr. Chow-Sing LinSimple Data Types - CH774 typedef enum {identifier_list} enum_type ; SYNTAX typedef enum {sunday, monday, tuesday, wednesday, thursday, friday, saturday} day_t ; Example

Enumerated Types Example Scans an integer representing an expense code and calls a function that uses a switch statement to display the code meaning Dr. Chow-Sing LinSimple Data Types - CH775

Dr. Chow-Sing LinSimple Data Types - CH776

Enumeration constants must be identifiers – Cannot be numeric, character, or string literals Type definitions immediately after any #define and #include directives – So it can be accessed through all part of your program. The reserved word typedef can be used to name many varieties of user-defined types. Dr. Chow-Sing LinSimple Data Types - CH777

Example 7.12 If today tomorrow are type day_t variables The following if statement assigns the value of tomorrow based on the value of today Because the days of a week are cyclical – tomorrow should be set to Sunday when today is Saturday Dr. Chow-Sing LinSimple Data Types - CH778 if (today == saturday) tomorrow = sunday; else tommorrow = (day_t) (today + 1)

Example 7.12 (Cont.) The last value(saturday) in type day_t is treated separately – Because adding 1 to its integer representation yields a result not associated with a valid day_t value C provides no range checking to verify that the value stored in an enumerated type variable is valid – today = saturday + 3 ;  no runtime error although it is clearly invalid. Dr. Chow-Sing LinSimple Data Types - CH779

Exercises for Section 7.7 Evaluate each of the following expressions – assuming before each operation that the value of variable today (type day_t) is thursday Dr. Chow-Sing LinSimple Data Types - CH780 typedef enum {monday, tuesday, wednessday, thursday, friday, saturday, sunday} dat_t ; Answer (int) monday0 today < tuesday0 (False) (day_t) (today – 1)wednesday

Multidimensional Arrays An array with two or more dimensions Dr. Chow-Sing LinArrays - CH881 element-type aname[size 1 ] [size 2 ] … [size n ];/* storage allocation */ element-type aname[ ] [size 2 ] … [size n ]/* parameter in prototype */ SYNTAX double table[NROWS] [NROWS];/* storage allocation */ void process_matrix (int in[] [4],/* input parameter */ int out[] [4],/* output parameter */ int nrows)/* input – number of rows */ Example The size of the first dimension (the number of rows) is the only size that can be omitted!!

Multidimensional Arrays (Cont.) The array declaration char tictac[3] [3]; – Allocates storage for a two-dimensional array (tictac) Three rows and three columns – This array has nine elements Each of which must be referenced – row subscript (0, 1, or 2) – Column subscript (0, 1, or 2) – Each array element contains a character value Dr. Chow-Sing LinArrays - CH882

Multidimensional Arrays (Cont.) Dr. Chow-Sing LinArrays - CH883 tictac [1][2]

Example 7.14 The array table double table[7][5][6] ; Consists of three dimensions – The first subscript Values from 0 to 6 – The second subscript Values from 0 to 4 – The third subscript Values from 0 to 5 Dr. Chow-Sing LinArrays - CH884

Example 7.14 (Cont.) A total of 7X5X6, or 210, type double values may be stored in the array table In order to access a single number, table[2][3][4], all three subscripts must be specified in each reference to array table Dr. Chow-Sing LinArrays - CH885

Initialization Multidimensional Arrays Just like initialize one-dimensional arrays The value are usually grouped by rows – Instead of listing all table values in one list For example – Declare a tic-tac-toe board and initialize its contents to blanks Dr. Chow-Sing LinArrays - CH886 char tictac[3][3] = { {‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}, {‘ ‘, ‘ ‘, ‘ ‘}};

Figure 7.21 Function to Check Whether Tic-tac-toe Board Is Filled Dr. Chow-Sing LinArrays - CH887

Array with Several Dimensions The array enroll declared here Dr. Chow-Sing LinArrays - CH888 int enroll [MAXCRS][5][4]; course campus year

Array with Several Dimensions (Cont.) Array enroll is composed of a total of 2000 (100 X 5 X 4) elements When you are dealing with multidimensional arrays, a potential pitfall exists. – If several multidimensional arrays are declared in the same program, memory space can be used up rapidly. – Be aware of amount of memory space required by each large array in a program. Dr. Chow-Sing LinArrays - CH889

Example 7.16 Find and display the total number of students in each course for (course = 0 ; course<MASCRS; ++course) { crs_sum=0; for (campus=0; campus<5; ++campus) { for (cls_rank = 0; cls_rank < 4; ++cls_rank) { crs_sum += enroll[course][campus][cls_rank]; } printf(“Number of students in course %d is %d\n”, course, crs_sum); } Dr. Chow-Sing LinArrays - CH890

Array Processing Illustrated Sequential access – Process the table rows or columns in sequence – Starting with the first and ending with the last Random access – Access to element i + 1 of an array does not necessarily occur right after access to element i Dr. Chow-Sing LinArrays - CH891

Case Study – Summary of Hospital Revenue Read Book Page 439 ~ 446 Dr. Chow-Sing LinArrays - CH892

Case Study (Cont.) Read Book Page 439 ~ 446 Dr. Chow-Sing LinArrays - CH893

Figure 7.24 Hospital Revenue Summary Main Function

Figure 7.25 Function scan_table and Helper Function initialize

Figure 7.25 Function scan_table and Helper Function initialize (cont’d)

Figure 7.26 Function display_table and Helper Functions display_quarter and whole_thousands

1-99 Figure 7.26 Function display_table and Helper Functions display_quarter and whole_thousands (cont’d)

Common Programming Errors Subscript-range error – When the subscript value used is outside the range specified by the array declaration An out-of-range reference occurs – For the array celsius, int celsius[100]; When celsius is used with a subscript – value less than 0 or greater than 99  a subscript-range error occurs Dr. Chow-Sing LinArrays - CH8100

Common Programming Errors (Cont.) Subscript-range error – If the value of i is 150 A reference to the subscripted variable celsius[i] may cause message In ANSI C, the prevention of subscript-range errors is entirely the responsibility of the programmer. – Subscript-range errors are not syntax errors – They are not detected until program execution Dr. Chow-Sing LinArrays - CH8101 access violation at line no. 28

Common Programming Errors (Cont.) Do remember to use the & on an array element that is being passed as an output argument Use, int z[], to declare array parameters, instead of int *z, for declaring array input and output parameters in function prototype. Dr. Chow-Sing LinArrays - CH8102