Arrays as Function Parameters. CSCE 1062 Outline  Passing an array argument (section 9.3)  Reading part of an array (section 9.4)  Searching and sorting.

Slides:



Advertisements
Similar presentations
Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
Advertisements

One Dimensional Arrays
Chapter 9 Data Structures: Arrays and Structs Lecture Notes Prepared By: Blaise W. Liffick, PhD Department of Computer Science Millersville University.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Passing Arrays to Functions Programming. COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 2 Passing Arrays as Parameters l Arrays are.
 Sort: arrange values into an order  Alphabetical  Ascending numeric  Descending numeric  Does come before or after “%”?  Two algorithms considered.
Lecture 22: Arrays (cont). 2 Lecture Contents: t Searching in array: –linear search –binary search t Multidimensional arrays t Demo programs t Exercises.
Data Structures Arrays and Structs Chapter The Array Data Type t Array elements have a common name –The array as a whole is referenced through.
Starting Out with C++, 3 rd Edition 1 Chapter 8 – Searching and Sorting Arrays.
Arrays Arrays are data structures consisting of data items of the same type. Arrays are ‘static’ entities, in that they remain the same size once they.
Engineering Problem Solving With C++ An Object Based Approach Chapter 6 One-Dimensional Arrays.
1 11/27/06CS150 Introduction to Computer Science 1 Searching Arrays.
Passing Arrays to Functions. COMP104 Lecture 16 / Slide 2 Array Element Pass by Value * Individual array elements can be passed by value or by reference.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
C++ Plus Data Structures
 2003 Prentice Hall, Inc. All rights reserved. 1 Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
C++ for Engineers and Scientists Third Edition
Searching and Sorting Arrays
Programming Sorting Arrays. COMP104 Lecture 25 / Slide 2 Sorting l To arrange a set of items in sequence. l It was estimated that 25~50% of all computing.
Pass by Reference. COMP104 Pass by Reference / Slide 2 Passing Parameters by Reference * To have a function with multiple outputs, we have to use pass.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12: Recursion Problem Solving, Abstraction, and Design using C++
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Chapter 6 One-Dimensional Arrays ELEC 206 Computer Tools for Electrical Engineering.
Searching and Sorting Chapter Sorting Arrays.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides:
Searching and Sorting, Template Functions, and Vectors ITK 169 Fall 2003.
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.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Sorting. Algorithms Sorting reorders the elements in an array or list in either ascending or descending order. Sorting reorders the elements in an array.
1 Lecture 8 Arrays Part II Sorting Arrays Sorting data  Important computing application  Virtually every organization must sort some data Massive.
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.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Sorting CS Sorting means... Sorting rearranges the elements into either ascending or descending order within the array. (we’ll use ascending order.)
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
More Array Access Examples Here is an example showing array access logic: const int MAXSTUDENTS = 100; int Test[MAXSTUDENTS]; int numStudents = 0;... //
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.
Modular Programming – User Defined Functions. CSCE 1062 Outline  Modular programming – user defined functions  Value returning functions  return statement.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
1 Chapter 13-2 Applied Arrays: Lists and Strings Dale/Weems.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
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.
1 11/12/04CS150 Introduction to Computer Science 1 More Arrays.
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Lecture 21: Arrays. 2 Lecture Contents: t Declaring and referencing arrays t Array subscripts t Using for/while loops for sequential access t Demo programs.
SORTING Sorting is storage of data in some order, it can be in ascending or descending order. The term Sorting comes along-with the term Searching. There.
Starting Out with C++, 3 rd Edition 1 Sorting Arrays.
Chapter 5 Arrays Copyright © 2016 Pearson, Inc. All rights reserved.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Arrays + Functions Outline 6.5Passing Arrays to Functions.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Prof. Amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 7. 1-D & 2-D Arrays.
Common Elementary Algorithms Some of the basic but frequently used algorithms for manipulating arrays. These algorithms are so important that: a)Some programming.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Engineering Problem Solving with C++, Etter
C++ Programming Lecture 15 Arrays – Part II
C++ Programming Lecture 15 Arrays – Part II
Chapter 8 – Searching and Sorting Arrays
Chapter 9: Data Structures: Arrays
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
Presentation transcript:

Arrays as Function Parameters

CSCE 1062 Outline  Passing an array argument (section 9.3)  Reading part of an array (section 9.4)  Searching and sorting arrays (section 9.5)  Finding the smallest value in an array  Array search  Sorting an array in ascending order

CSCE 1063 Bubble Sort #include using namespace std; void exchange(float& a1, float& a2); void main() { float x[] = {74.1, 45.2, 83.5, 16.6, 7.8}; for (int i=0; i<4; i++) for (int j = i+1; j<5; j++) if (x[i] < x[j]) exchange(x[i], x[j]); for (j = 0; j<5; j++) cout << “ ” << x[j]); } void exchange(float& a1, float& a2) { float temp = a1; a1 = a2; a2 = temp; }

CSCE 1064 Passing an Array Argument  Arrays are always passed by reference  Pass entire array to a function by writing just its name (no subscripts or brackets) in the argument list of the function call (actual parameters)  In function definition and prototype, use empty square brackets ([ ]) to identify array  Use keyword const to indicate that array argument cannot be changed by function

CSCE 1065 Example 1 – Comparing 2 Arrays const int MAX_SIZE = 5; float x[MAX_SIZE ]; float y[MAX_SIZE ];... if (sameArray(x, y, MAX_SIZE)) cout << “Arrays are identical.” << endl; else cout << “Arrays are different.” << endl;

CSCE 1066 Listing 9.4 Function sameArray

CSCE 1067 Example 2 – Adding 2 Arrays const int MAX_SIZE = 5; float x[MAX_SIZE ] = {1.8, 2.2, 3.4, 5.1, 6.7}; float y[MAX_SIZE ] = {2.0, 4.5, 1.3, 4.0, 5.5}; float z[MAX_SIZE];... addArray(MAX_SIZE, x, y, z);

CSCE 1068 Listing 9.5 Function addArray // File: addArray.cpp // Stores the sum of a[i] and b[i] in c[i] // Sums pairs of array elements with subscripts ranging from 0 //to size – 1 // Pre: a[i] and b[i] are defined (0 <= i <= size-1) // Post: c[i] = a[i] + b[i] (0 <= i <= size-1) void addArray (int size,// IN: the size of the arrays const float a[],// IN: the first array const float b[],// IN: the second array float c[])// OUT: result array { // Add corresponding elements of a and b and store in c for (int i = 0; i < size; i++) c[i] = a[i] + b[i]; }

CSCE 1069 Reading Part of an Array  Sometimes it is difficult to know how many elements will be in an array  34 students in one section  28 students in another section  Always allocate enough space for largest possible amount needed (e.g. 40 for students in a section)  Remember to start reading with index [0]  Must keep track of how many elements used

CSCE Searching and Sorting Arrays  Two common array processing problems  Searching  Sorting  E.g.  look for a particular score, highest score, etc.  rearrange an array of scores in increasing order

CSCE Array Search – Function Algorithm 1. For each array element 1.1 If the current element contains the target 1.2 Return the subscript of the current element 2. Return -1.

CSCE Array Search Function Analysis (Interface)  Input arguments  int items[ ]// array to search  int size// number of items in array  int target// item to find  Output arguments  none  Returns  if found, subscript of first location in array  if not found, -1

CSCE Listing 9.9 The function linSearch

CSCE Finding the Smallest Value 1. Assume the first element is smallest so far and save its subscript 2. For each array element after the first one 2.1 If the current element < the smallest so far Save the subscript of current element

CSCE Function findIndexOfMin // Finds the subscript of the smallest value in a subarray. int findIndexOfMin(float z[], int start, int end) { // local data int minIndex, // index of the smallest element i; // Assume the first element of subarray is the smallest minIndex = start; for (i = start + 1; i<=end; i++) if (z[i] < z[minIndex]) minIndex = i; // Returns the subscript of the smallest value in the subarray. return minIndex; }

CSCE Sorting an Array in Ascending Order  Many programs execute more efficiently if data is in order before processing starts  Possible to order in either ascending or descending arrangement  Selection sort just one of many ways to do this  reuses previous components/functions of search and swap

CSCE Selection Sort - Algorithm 1. Starting with the first item in the array (subscript 0) and ending with the next-to-last- item: 1.1 Set i equal to the subscript of the first item in the subarray to be processed in the next steps 1.2 Find the subscript (minSub) of the smallest item in the subarray with subscripts ranging from i through n Exchange the smallest item found in step 1.2 with item i

CSCE Selection Sort Function Analysis  Input arguments float items[ ]// array to sort int n// number of items to sort  Output arguments float items [ ]// original array sorted  Local variables int i// subscript of first element int minSub// subscript of smallest item

CSCE Function selSort void selSort(float y[], int n) { int minSub; for (int i=0; i<n-1; i++) { // Find index of smallest item in unsorted section. minSub = findIndexOfMin(y, i, n-1); // Exchange items at position minSub and i. exchange(y[minSub], y[i]); } }

CSCE #include using namespace std; void exchange(float& a1, float& a2); void selSort(float y[], int n); int findIndexOfMin(float[], int, int); void main() { const int size = 4; float x[] = {74.1, 45.2, 83.5, 16.6}; selSort(x, size); } void exchange(float& a1, float& a2) { float temp; temp = a1; a1 = a2; a2 = temp; } void selSort(float y[], int n) { int minSub; for (int i=0; i<n-1; i++) { minSub = findIndexOfMin(y, i, n-1); exchange(y[minSub], y[i]); } } int findIndexOfMin(float z[], int start, int end) { int minIndex, int i; minIndex = start; for (i = start + 1; i<=end; i++) if (z[i] < z[minIndex]) minIndex = i; return minIndex; }

CSCE Next lecture we will revise