Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 31 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
31
Dung lượng
472,5 KB
Nội dung
C++ Programming Lecture 15 Arrays – Part II The Hashemite University Computer Engineering Department (Adapted from the textbook slides) Outline Introduction Passing arrays to functions Sorting arrays Multisubscripted arrays Examples The Hashemite University Introduction In this lecture we will see how we can deal with arrays as ordinary variables and pass them to functions as parameters Also, we will examine algorithms to sort the elements found in an array either in: Ascending order Or descending order Finally, we will see how to create and initilaize multi-dimensional arrays The Hashemite University Passing Arrays to Functions I You can pass an array to a function like any other variable with some differences Function prototype: you must tell the compiler that the passed parameter is an array Function call: just pass the name of the array in the function call like any other variable Function definition: copy the prototype as the function header and specify the names of the variables The Hashemite University Passing Arrays to Functions II Function prototype: void modifyArray( int b[], int arraySize ); Parameter names optional in prototype int b[] could be simply int [] int arraysize could be simply int If the size of the array is passed as, e.g int b[5], the compiler will ignore it The Hashemite University Passing Arrays to Functions III Function Call: Specify the name without any brackets To pass array myArray declared as int myArray[ 24 ]; to function myFunction, a function call would resemble myFunction( myArray, 24 ); Array size is usually passed to the function to allow correct processing of the array elements The Hashemite University Passing Arrays to Functions IV Arrays are passed as call-by-reference by default Value of name of array is address of the first element Function knows where the array is stored Modifies original memory locations Individual array elements are passed by callby-value pass subscripted name (i.e., myArray[ ]) to function If you want to pass an element by reference then you must use reference variables To prevent a function from modifying an array declare the parameter array within both the function definition and the function prototype as a const (i.e pass it as readonly variable) So, any modification will be reported as a syntax error The Hashemite University Calling array by value and by reference (1) void modify (int [] ); int main() { int array1[4]={2,4,6,8}; modify(array1); cout