Arrays and Records.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Programming and Data Structure
Searching and Sorting an Array 4 Searching and sorting are two fundamental algorithms often implemented with arrays –Search an array to determine the location.
ICS103: Programming in C Searching, Sorting, 2D Arrays
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.
1 CS 201 Passing Function as Parameter & Array Debzani Deb.
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 5 - Arrays CSC 200 Matt Kayala 2/27/06. Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays.
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
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
 2007 Pearson Education, Inc. All rights reserved C 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
CSEB114: PRINCIPLE OF PROGRAMMING Chapter 8: 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 8 Arrays and Strings
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.
ARRAYS 1 Week 2. Data Structures  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently 
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
Chapter 8 Arrays Instructor: Kun-Mao Chao ( 台大資工 趙坤茂 )
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
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.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
Chapter 5 Arrays. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 5-2 Learning Objectives  Introduction to Arrays  Declaring and referencing.
ICS103 Programming in C Lecture 11: Arrays I
ICS103: Programming in C Searching, Sorting, 2D Arrays Muhamed F. Mudawar.
Chapter 7 Arrays. Introductions Declare 1 variable to store a test score of 1 student. int score; Declare 2 variables to store a test score of 2 students.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
UNIT-4 1. Arrays: Definition and declaration, Initialization, Accessing elements of arrays, Storing values in arrays, Inter-function Communication: Passing.
1 Chapter 7 Arrays. 2 Outline and Objective In this chapter we will Learn about arrays One-dimensional arrays Two-dimensional arrays Learn about searching.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
ICS103: Programming in C 7: Arrays Muhamed F. Mudawar.
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.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Problem Solving and Program Design in C Chap. 7 Arrays Chow-Sing Lin.
KUKUM-06/07 EKT120: Computer Programming 1 Week 6 Arrays-Part 1.
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 Chapter 7.
ARRAYS.
EGR 2261 Unit 10 Two-dimensional Arrays
Computer Programming BCT 1113
Chapter 7 Part 1 Edited by JJ Shepherd
Chapter 7 Arrays.
Arrays … The Sequel Applications and Extensions
C Arrays.
Chapter 6 - Arrays Outline 6.1 Introduction 6.2 Arrays
7 Arrays.
EKT150 : Computer Programming
ICS103 Programming in C Lecture 13: Arrays II
Review of Arrays and Pointers
Data Structures (CS212D) Week # 2: Arrays.
Arrays Week 2.
7 Arrays.
Chapter 9: Data Structures: Arrays
ICS103 Programming in C Lecture 12: Arrays I
ICS103: Programming in C Searching, Sorting, 2D Arrays
Presentation transcript:

Arrays and Records

Overview To solve many programming problems, it is more efficient to group data items together in main memory than to allocate an individual memory cell for each variable. C allows a programmer to group such related data items together into a single composite data structure. In this chapter, we look at one such data structure: the array, which is a collection of data items of the same type.

Introduction to arrays, sequential access, and array arguments (CHAPTER 7.1-7.5)

Declaring and Referencing Arrays An array is a collection of two or more adjacent memory cells, called array elements. Declaration double x[8]; instructs the compiler to associate eight memory cells with the 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 so, eight double number may be stored and referenced using the array name x

Example 7.1 Array x Statements that manipulate array x double x[8]; 16.0 12.0 6.0 8.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

Example 7.1 Array x Statements that manipulate array x double x[8]; 16.0 12.0 6.0 8.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); // Display the value of x[0], which is 16.0 x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

Example 7.1 Array x Statements that manipulate array x double x[8]; 16.0 12.0 6.0 25.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; // Stores the value 25.0 in x[3] sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

Example 7.1 Array x Statements that manipulate array x double x[8]; 16.0 12.0 6.0 25.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; sum = x[0] + x[1]; // Stores x[0] + x[1], 28.0, in variable sum sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1];

Example 7.1 Array x Statements that manipulate array x double x[8]; 16.0 12.0 6.0 25.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; // Adds x[2] to sum, 28.0 + 6.0 = 34.0 x[3] += 1.0; x[2] = x[0] + x[1];

Example 7.1 Array x Statements that manipulate array x double x[8]; 16.0 12.0 6.0 26.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; // Adds 1.0 to x[3], 25.0 + 1.0 = 26.0 x[2] = x[0] + x[1];

Example 7.1 Array x Statements that manipulate array x double x[8]; 16.0 12.0 28.0 26.0 2.5 14.0 -54.5 Statements that manipulate array x printf(“%.lf”, x[0]); x[3] = 25.0; sum = x[0] + x[1]; sum += x[2]; x[3] += 1.0; x[2] = x[0] + x[1]; // Stores x[0] + x[1], 16.0 + 12.0 = 28.0 in x[2]

Initializing Arrays You can declare a variable without initialization double average; /* Not initialized */ You can also declare a variable with initialization int sum = 0; /* Initialized to 0 */ Similarly, you can declare arrays without initialization double x[20]; /* Not initialized */ You can also declare an array and initialize it int prime[5] = {2, 3, 5, 7, 11}; No need to specify the array size when initializing it int prime[] = {2, 3, 5, 7, 11};

Array Initialization In the following statement, we initialize a 25-element array with the prime numbers less than 100. 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}; Array element prime_lt_100[24] is 97

Storing a String in an Array of Characters If the list is long, you can use string instead of an initialization list char vowels[] = “This is a long string”; In this case, vowels[0] stores ‘T’, vowels[1] stores ‘h’, and so on.

Visualizing an Array in Memory /* Array A has 6 elements */ int A[] = {9, 5, -3, 10, 27, -8}; 342900 342904 342908 342912 342916 342920 Memory Addresses 9 5 -3 10 27 -8 Array A 1 2 3 4 All arrays start at index 0 Array Index (subscript) Array Element

Array Subscripts Array subscript is used to differentiate between the individual array elements and to specify which array element is to be manipulated. The value of this subscript must be an integer between 0 and one less than the declared size of the array. Example: x[0] x[1] x[2] x[3] x[4] x[5] x[6] Subscripted variable x [ i ] , jika nilai i =2, maka subscript value =2

Array Subscripts Example: Array x Statement Explanation 16.0 12.0 6.0 8.0 2.5 14.0 -54.5 Statement Explanation i = 5; printf(“%d %.lf”, 4, x[4]); Displays 4 and 2.5 (value of x[4]) printf(“%.lf”, x[i] + 1) Display 13.0 (value of x[5] plus 1) printf(“%.lf”, x[i +1]) Display 14.0 (value of x[6]) printf(“%.lf”, x[i] + i) Display 17.0 (value of x[5] plus 5) printf(“%.lf”, x[2*i - 3]) Display -54.5 (value of x[7])

Array Subscripts Example: Array x Statement Explanation 16.0 12.0 6.0 8.0 2.5 14.0 -54.5 Statement Explanation i = 5; printf(“%d %.lf”, x[(int)x[4]]); Displays 6.0 (value of x[2]) printf(“%.lf”, x[i++]) Display 12.0 (value of x[5]) then assign 6 to i printf(“%.lf”, x[--i]) Assign 5 (6-1) to i and then display 12.0 (value of x[5])

Using for Loops for Sequential Access In C, we can process the elements of an array in sequence using an indexed for loop, a counting loop whose loop control variable runs from 0 to one less than the array size. Example: (assume SIZE has been defined to be 11) int square[SIZE], i; for (i=0; i < SIZE; i++) square[i] = i * i; [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] 1 4 9 16 25 36 49 64 81 100

Using for Loops for Sequential Access Statistical Computations Using Arrays One common use of arrays is for storage of a collection of related data values, which are used to perform some simple statistical computations. Example: sum = 0; for (i = 0; i < MAX_ITEM; i++){ sum += x[i]; }

Using for Loops for Sequential Access sum_sqr = 0; for (i = 0; i < MAX_ITEM; i++){ sum_sqr += x[i] * x[i]; } st_dev = sqrt(sum_sqr / MAX_ITEM – mean * mean);

Using Array Elements as Function Arguments The call printf(“%3d%4c%9.2f%5c%9.2f\n”, i, ‘ ‘, x[i], ‘ ‘, x[i] - mean); uses array element x[i] as an input argument to function printf. scanf(“%lf”, &x[i]); uses array element x[i] as an output argument to function scanf.

Using Array Elements as Function Arguments Suppose that we have a function do_it defined as: void do_it(double x, double *p1, double *p2) { *p1 = x + 5; *p2 = x * x; } Let y be an array of double elements declared as: double y[6]; /* not initialized */ y[0] = 3.0; /* initialize y[0] */ We can call the function do_it as follows: do_it(y[0], &y[1], &y[2]); It will change the values of y[1] and y[2]

do_it(y[0], &y[1], &y[2]) Data Area of Caller do_it Data Area Array y x y[0] y[1] y[2] y[3] y[4] y[5] 3.0 8.0 9.0 ? 3.0 p1 &y[1] p2 &y[2]

Array Arguments Argument Correspondence for Array Parameters To call function fill_array, you must specify the actual array argument, the number of array elements, and the value to be stored in the array. If y is an array with ten type int elements, the function call fill_array(y, 10, num); stores the value of num in the ten elements of array y.

Calling Function fill_array To call fill_array, you must pass 3 arguments: Actual array name to fill Number of array elements to fill Value to store in array Examples of calling fill_array: /* fill 5 elements of x with 1 */ fill_array(x, 5, 1); /* fill 10 elements of y with num */ fill_array(y, 10, num);

fill_array(x, 5, 1); The address of array x is passed to list

Array Arguments Argument Correspondence for Array Parameters In the declaration for function fill_array, we can use either parameter declaration: int list[] int *list The first tells us that the actual argument is an array. However, the second declaration would be equally valid for an integer array parameter as C passes an array argument py passing the address of its initial element.

Arrays as Input Arguments The const keyword indicates that list[] is an input parameter that cannot be modified by the function /* Returns the max in an array of n elements */ /* Pre: First n elements of list are defined */ double get_max(const double list[], int n) { int i; double max = list[0]; for (i=1; i<n; ++i) if (list[i] > max) max = list[i]; return max; }

Array Arguments Returning an Array Result In C, defining a function of the variety modeled in the figure below requires use of an output parameter to send the result array back to the calling module. input array (output parameters result parameter) When we use simple output parameters, the calling function must declare variables into which the function subprogram will store its results. function

Array Arguments Returning an Array Result Example: void add_arrays (const double ar1[], const double ar2[], double arsum[], int n) { int i; /* Adds corresponding elements of ar1 and ar2 */ for (i=0; i<n; i++) arsum[i] = ar1[i] + ar2[i]; }

The formal parameter list declaration const double ar1[ ], const double ar2[ ], double arsum[ ], int n indicates that formal parameters ar1 , ar2 , and arsum stand for actual argument arrays whose elements are of type double and that ar1 and ar2 are strictly input parameters, as is n . The function can process type double arrays of any size as long as the preconditions stated in the initial block comment are met. If we assume that a calling function has declared three five-element arrays x , y , and x_plus_y and has filled x and y with data, the call add_arrays(x, y, x_plus_y, 5); would lead to the memory setup pictured

Partially Filled Arrays The format of array declaration requires that we specify the array size at the point of declaration Moreover, once we declare the array, its size cannot be changed. The array is a fixed size data structure There are many programming situations where we do not really know the array size before hand For example, suppose we want to read test scores from a data file and store them into an array, we do not know how many test scores exist in the file. So, what should be the array size?

Partially Filled Arrays (cont'd) One solution is to declare the array big enough so that it can work in the worst-case scenario For the test scores data file, we can safely assume that no section is more than 50 students We define the SIZE of the array to be 50 However, in this case, the array will be partially filled

Array Arguments Partially Filled Arrays To reuse an array for processing more than one data set, the programmer often declares an array large enough to hold the largest data set anticipated. int main(void) { double arr[A_SIZE]; int in_use, i; fill_to_sentinel(A_SIZE, SENT, arr, &in_use); printf(“List of data values\n”); for (i=0; i<in_use; i++) printf(“%l3.3f\n”, arr[i]); return (0); }

SEARCHING AND SORTING AN ARRAY (CHAPTER 7.6)

Searching Traversing an array to locate a particular item It requires the user to specify the target item If the target item is found, its index is returned If the target item is NOT found, -1 is returned Two searching algorithms Linear Search (works with any array) Binary Search (works if the searched array is sorted)

Linear Search Algorithm Initialize a flag (zero) to indicate whether target is found Start at the first array element (at index 0) Repeat while the target is not found and there are more array elements If the current element matches the target then Set the flag to indicate that the target is found Else, Advance to the next array element If the target is found then Return the target index as the search result Else, Return -1 as the search result

Linear Search Implementation /* Search array a[] for target using linear search * Returns index of target or -1 if not found */ int linear_search(const int a[], int target, int n) { int i = 0, found = 0; while (!found && i<n) { if (a[i] == target) found = 1; else ++i; } if (found) return i; else return -1;

Binary Search Algorithm If an array is ordered, it is a waste of time to look for an item using linear search. It would be like looking for a word in a dictionary sequentially. Binary search works by comparing the target with the item at the middle of the array: If the target is the middle item, we are done. If the target is less than the middle item, we search the first half of the array. If the target is bigger than the middle item, we search the second half of the array. Repeat until target is found or nothing to search

Binary Search first mid last 5 11 target = 22 4 7 8 10 14 21 22 36 54 71 85 92 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] first mid last 6 8 11 4 7 10 14 21 22 36 54 71 85 92 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 22>21 first mid last 6 7 4 8 10 14 21 22 36 54 71 85 92 [0] [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] 22<54 22==22

Sorting an Array Algorithm for each value of fill from 0 to n-1 Find index_of_min, the index of the smallest element in the unsorted subarray list[fill] through list[n-1]. If fill is not the position of the smallest element (index_of_min) Exchange the smallest element with the one at position fill.

Sorting an Array Trace of Selection Sort fill is 0. [0] [1] [2] [3] 74 45 83 16

Sorting an Array Trace of Selection Sort fill is 0. Find the smallest element in subarray list[0] through list[3] and swap it with list[0]. [0] [1] [2] [3] 74 45 83 16

Sorting an Array Trace of Selection Sort fill is 0. Find the smallest element in subarray list[1] through list[3] and swap it with list[0]. [0] [1] [2] [3] 74 45 83 16

Sorting an Array Trace of Selection Sort fill is 0. Find the smallest element in subarray list[1] through list[3] and swap it with list[0]. [0] [1] [2] [3] 16 45 83 74

Sorting an Array Trace of Selection Sort fill is 1. Find the smallest element in subarray list[1] through list[3] and swap it with list[1]. [0] [1] [2] [3] 16 45 83 74

Sorting an Array Trace of Selection Sort fill is 1. Find the smallest element in subarray list[1] through list[3] and swap it with list[1]. No exchange needed. [0] [1] [2] [3] 16 45 83 74

Sorting an Array Trace of Selection Sort fill is 2. Find the smallest element in subarray list[2] through list[3] and swap it with list[2]. [0] [1] [2] [3] 16 45 83 74

Sorting an Array Trace of Selection Sort fill is 2. Find the smallest element in subarray list[2] through list[3] and swap it with list[2]. [0] [1] [2] [3] 16 45 83 74

Sorting an Array Trace of Selection Sort fill is 2. Find the smallest element in subarray list[2] through list[3] and swap it with list[2]. [0] [1] [2] [3] 16 45 74 83

Sorting an Array Trace of Selection Sort fill is 2. Find the smallest element in subarray list[2] through list[3] and swap it with list[2]. [0] [1] [2] [3] 16 45 74 83

Sorting an Array Trace of Selection Sort [0] [1] [2] [3] 16 45 74 83

Sorting an Array

Smallest Element in Sub-Array /* Find the smallest element in the sub-array list[first] * through list[last], where first<last * Return the index of the smallest element in sub-array */ int get_min_range(int list[], int first, int last) { int i; int index_min = first; for (i=first+1; i<=last; i++) { if (list[i] < list[index_min]) index_min = i; } return index_min;

PARALLEL ARRAYS, ENUMERATED TYPES, AND MULTIDIMENSIONAL ARRAYS (CHAPTER 7.7 & 7.8)

Two-Dimensional Arrays A 2D array is a contiguous collection of elements of the same type, that may be viewed as a table consisting of multiple rows and multiple columns. To store the grades of 30 students in five courses, it is better to use a 2D array than five 1D arrays. Column Row 1 2 3

2D Array Declaration A 2D array is declared by specifying the type of element, the name of the variable, followed by the number of rows and the number of columns As with 1D arrays, it is a good practice to declare the row and column sizes as named constants: #define ROWS 3 #define COLS 4 . . . int table[ROWS][COLS]; Both rows and columns are indexed from zero. Column Row 1 2 3

Indexing 2D Arrays A 2D array element is indexed by specifying its row and column indices. The following statement stores 51 in the cell with row index 1, and column index 3: table[1][3] = 51; Here is another example: table[2][3] = table[1][3] + 6; 1 2 51 3 1 2 51 57 3 60

It is ok to omit the number of rows but not the number of columns Initializing 2D Arrays As with 1-D arrays, you can declare and initialize a 2D array at the same time. A nested list is used, where each inner list represents a row. For example: int table[][4] = {{1,2,2,5},{3,4,6},{5,6,7,9}}; If you provide less values than the declared size, the remaining cells are set to zero (NOT a good practice!) 1 2 3 5 4 6 7 9 It is ok to omit the number of rows but not the number of columns