Passing Arrays to Functions Programming. COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 2 Passing Arrays as Parameters l Arrays are.

Slides:



Advertisements
Similar presentations
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Advertisements

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.
Programming Functions: Passing Parameters by Reference.
Arrays Programming COMP102 Prog. Fundamentals I: Arrays / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g.,
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Simple Arrays COMP104 Lecture 11 / Slide 2 Arrays * An array is a collection of data elements that are of the same type (e.g., a collection of integers,characters,
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.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 8 Multidimensional.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 11a. The Vector Class.
Chapter 8 Arrays and Strings
CSE202: Lecture 14The Ohio State University1 Arrays.
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
CSE202: Lecture 16The Ohio State University1 Two Dimensional Arrays.
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
1 Arrays & functions Each element of an array acts just like an ordinary variable: Like any ordinary variable, you can pass a single array element to a.
Simple Arrays Programming COMP104 Lecture 12 / Slide 2 Arrays l An array is a collection of data elements that are of the same type (e.g., a collection.
Arrays.
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.
Chapter 7 Arrays. Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3 Programming with Arrays 7.4 Multidimensional Arrays.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 7 Single-Dimensional.
Chapter 8 Arrays and Strings
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
Chapter 6 Arrays.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 8 Multidimensional Arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 6 Arrays.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
More Array Access Examples Here is an example showing array access logic: const int MAXSTUDENTS = 100; int Test[MAXSTUDENTS]; int numStudents = 0;... //
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
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.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
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.
© Copyright 2013 by Pearson Education, Inc. All Rights Reserved. 1 Chapter 7 Single-Dimensional Arrays and C-Strings.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Opening Input/Output Files ifstream infile; ofstream outfile; char inFileName[40]; char outFileName[40]; coutinFileName;
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Arrays Chapter 12. One-Dimensional Arrays If you wanted to read in 1000 ints and print them in reverse order, it would take a program that’s over 3000.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Arrays float Scores[9]; ? index: element // one dimensional array 1.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
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.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
Arrays float Scores[9]; ? index: element // one dimensional array 2.
Lesson 9 Arrays. Miscellaneous About Arrays An array is an object. Because of this, the array name is a reference variable Therefore, in order to start.
Objectives You should be able to describe: One-Dimensional Arrays
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
The Ohio State University
Chapter 6 Arrays DDC 2133 Programming II.
Chapter 6 Arrays Lecturer: Mrs Rohani Hassan
Engineering Problem Solving with C++, Etter
CS 1430: Programming in C++.
Arrays.
Multidimensional Arrays
Review of Everything Arrays
Chapter 7 Single-Dimensional Arrays and C-Strings
COMS 261 Computer Science I
Chapter 9: Data Structures: Arrays
Introducing Arrays Array is a data structure that represents a collection of the same types of data. From resourses of Y. Daniel Liang, “Introduction.
COMS 261 Computer Science I
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:

Passing Arrays to Functions Programming

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 2 Passing Arrays as Parameters l Arrays are always passed by reference. l The “[ ]” in the formal parameter specification indicates that the variable is an array. l It is a good practice to pass the dimension of the array as another parameter. l If the function must not change any element of the array then const should be used in the formal parameter specification of that array.

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 3 Smallest Value l Problem n Find the smallest value in a list of integers l Input n A list of integers and a value indicating the number of integers l Output n Smallest value in the list l Note n List remains unchanged after finding the smallest value!

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 4 Preliminary Design l Realizations n When looking for value with distinguishing characteristics, need a way of remembering best candidate found so far n Best written as a function - likely to be used often l Design n Search array looking for smallest value –Use a loop to consider each element in turn –If current element is smallest so far, then update smallest value so far candidate n When done examining all of the elements, the smallest value seen so far is the smallest value

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 5 Necessary Information l Information to be maintained n Array with values to be inspected for smallest value n Number of values in array n Index of current element being considered n Smallest value so far

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 6 A More Detailed Design l Solution: n Function that takes two parameters: an integer array and the array size; returns smallest value n Initialize smallest value to first element n For each of the other elements in the array –If it is smaller than the smallest value so far, update the value of the smallest value so far to current element n Quit at end of array and return smallest value seen as value of the function

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 7 int ListMinimum(const int Ar[], int asize) { int SmallestValueSoFar = Ar[0]; for (int i = 1; i < asize; ++i) { if (Ar[i] < SmallestValueSoFar ) { SmallestValueSoFar = Ar[i]; } return SmallestValueSoFar ; } Passing An Array Example 3 Notice empty brackets Could we just assign a 0 and have it work?

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 8 Using ListMinimum l What happens with the following? int Number[6] ={3, 88, -7, 9, 1, 24}; cout << ListMinimum(Number, 6) << endl; int List[3]; List[0] = 9; List[1] = 12; List[2] = 45; cout << ListMinimum(List, 3) << endl;

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 9 Some Useful Functions void DisplayList(const int Ar[], int asize) { for (int index = 0; index < asize; ++index) { cout << Ar[index] << " "; } cout << endl; } void GetList(int Ar[], int size){ for (int index = 0; index < Size; index++) { cin >> Ar[index]; }

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 10 Useful Functions Being Used const int MaxSize = 25; int Values[MaxSize]; GetList(Values,MaxSize ); DisplayList(Values, MaxSize);

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 11 Finding the Maximum element Entire array is passed by reference through address of the first element and dimension of the array. // Find the largest value in an array // input: n - number of elements to check // a[ ] - array of elements // output:index to the largest element #include int max_element(int size, const int a[]) { int max_index = 0; for (int i=1; i<size; i++) if (a[i] > a[max_index]) max_index = i; return max_index; } // end max_element;

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 12 Finding the Maximum element int main() { int A[10] = {9,8,7,6,5,4,10,2,1,0}; cout << “The maximum element of this array is: ” << A[max_element(10,A)] << endl; return 0; }

//Example 1:passing array elements to a function #include using namespace std; void print_square (int); const int ARRAY_SIZE = 5; int main(){ int index; int base[ARRAY_SIZE] = {3, 7, 2, 4, 5}; for(index = 0; index < ARRAY_SIZE; index++) print_square(base[index]); cout << endl; return 0; } void print_square(int number) { cout << " " << number * number; }

#include //Example 2: passing a whole array using namespace std; double average (int, const int[]); int main(){ const int array_size = 5; double ave; int base[array_size] = {3, 7, 2, 4, 5}; ave = average(array_size, base); cout << "The average of the numbers "; for (int index = 0; index < array_size; index++){ cout << base[index]; if ( index < array_size - 1) cout << ", "; } cout << " is " << ave << endl; return 0; }

//Example 2: passing a whole array double average( int size, const int inp_list[]) { double sum = 0.0; for ( int index = 0; index < size; index++) sum += inp_list[index]; return sum/size; }

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 16 Example 5 // Add a[i] and b[i] and store the sum in c[i] void add_array(int size, // in: array size double a[], // in: first array double b[], // in: second array double c[] ) // out: result array // array elements with subscripts ranging from // 0 to size-1 are added element by element // Pre: a[i] and b[i] (0<=i<=size-1) are defined // Post: c[i] = a[i] + b[i] (0<=i<=size-1) { int i; // Add a[i] and b[i] and store result in c[i] for (i=0; i < size; i++) c[i] = a[i] + b[i]; }

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 17 Example 5 int main() { const int size = 5; double x[size] = {1.8, 2.2, 3.4, 5.1, 6.7}, y[size] = {2.0, 4.5, 1.3, 4.0, 5.5}, z[size]; int ind; add_array(size, x, y, z); cout << "Content of array z is: \n"; for (i = 0; i < size; i++) cout << "z[" << i << "] is " << z[i] << endl; return 0; }

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 18 add_array (5, x, y, z );

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 19 Passing Two-Dimensional Arrays to Functions You can pass a two-dimensional array to a function; however, C++ requires that the column size to be specified in the function declaration. Example 6 gives an example with a function that sum up two two-dimensional array into a third one.

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 20 Example 6 // Sum up two 2-dimensional arrays into a third one #include using namespace std; const int max_cols = 5; // c[i][j] = a[i][j] + b[i][j] void add_array(double a[][max_cols], double b[][max_cols], double c[][max_cols], int rows) { int i, j; for (i=0; i < rows; i++) for (j=0; j < max_cols; j++) c[i][j] = a[i][j] + b[i][j]; }

int main() { const int max_rows = 2; double a[max_rows][max_cols] = {{1.8, 2.2, 3.4, 5.1, 6.7}, {1.0, 2.0, 3.0, 5.0, 6.0}}, b[max_rows][max_cols] = {{0.2, -0.2, -1.4, -3.1, -4.7}, {1.0, 0.0, -1.0, -3.0, -4.0}}, c[max_rows][max_cols]; int i, j; add_array(a, b, c, max_rows); // fix how decimals are shown cout.setf(ios::fixed); // use decimal notation cout.setf(ios::showpoint); // show decimals cout.precision(1); // one decimal place cout << "Content of array c is: \n"; for (i = 0; i < max_rows; i++){ for (j=0; j < max_cols; j++) cout << c[i][j] << ", "; cout << endl; } return 0; }

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 22 Pass-by-Reference void m(int, int []); int main() { int x = 1; // x represents an int value int y[10]; // y represents an array of int values y[0] = 1; // Initialize y[0] m(x, y); // Invoke m with arguments x and y cout << "x is " << x << endl; cout << "y[0] is " << y[0] << endl; return 0; } void m(int number, int numbers[]) { number = 1001; // Assign a new value to number numbers[0] = 5555; // Assign a new value to numbers[0] }

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 23 Reverse function list newList void reverse(const int list[], int newList[], int size) { for (int i = 0, j = size - 1; i < size; i++, j--) { newList[j] = list[i]; } int main(){ int list1[5] = {1, 2, 4, 5, 6}; int list2[5]; reverse(list1, list2,5); return 0; }

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 24 Reverse function list newList void add_array( double a[], // in: first array int size_a, double b[], // in: second array int size_b, double c[], int size_c) // out: result array //c[i] = a[i] + b[i] { for (int i = 0; i < size_c; i++) c[i] = 0; for (int i=0; i < size_a && i <size_c; i++) c[i] += a[i]; for (int i=0; i < size_b && i <size_c; i++) c[i] += b[i]; } int main() { double a[5] = {1,2,3,4,5}; double b[3] = {100,200,300}; double c[10]; add_array(a,5,b,3,c,10); for (int i = 0; i < 10; i++) cout << c[i] << endl; return 0; }

COMP102 Prog. Fundamentals I: Passing Arrays to Function / Slide 25 Problem: Counting Occurrence of Each Letter l Generate 100 lowercase letters randomly and assign to an array of characters. l Count the occurrence of each letter in the array. l //CountLettersInArray.cpp