Presentation is loading. Please wait.

Presentation is loading. Please wait.

EGR 2261 Unit 9 One-dimensional Arrays

Similar presentations


Presentation on theme: "EGR 2261 Unit 9 One-dimensional Arrays"— Presentation transcript:

1 EGR 2261 Unit 9 One-dimensional Arrays
Read Malik, pages in Chapter 8. Homework #9 and Lab #9 due next week. Exam #2 next week. Handouts: Quiz #8, Unit 9 practice sheets. Preview Exam #2.

2 Review from Unit 2: Data Types
Recall that a data type is a set of values together with a set of allowed operations on those values. C++ data types fall into three categories: Simple data types Structured data types Pointers C++ Programming: From Problem Analysis to Program Design, Seventh Edition

3 Simple versus Structured Data Types
Simple data types are the building blocks of structured data types. A variable of a simple data type can store only one value at a time. Examples: int, double, char, bool A variable of a structured data type is a collection of other data items. Examples: arrays (Chapter 8), structs (Chapter 9), classes (Chapter 10) C++ Programming: From Problem Analysis to Program Design, Seventh Edition

4 Partial Hierarchy of Data Types
Simple Data Types Integral (int, bool, char, …) Floating-Point (double, …) Enumeration Structured Data Types Arrays structs Classes Pointers

5 Arrays An array is a collection of a fixed number of elements (or “components”), all of the same data type. For example, an array might contain: Five elements, each of which is an int. One hundred elements, each of which is a double. Seven thousand elements, each of which is a char. Most people use the word element. Malik often says component, but I’ll avoid this. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

6 Why are Arrays Useful? The program on page 506 shows how (without using arrays) to find and display the average of five test scores, along with a list of the scores that are less than the average. See next slide. Doing it this way is not bad for five test scores, but what if you had 100 test scores? C++ Programming: From Problem Analysis to Program Design, Seventh Edition

7 Non-Array Example from p. 506 (Example 8-4 on p
Non-Array Example from p. 506 (Example 8-4 on p. 514 shows how to do it with arrays.) Run it (weeok09NonArrayTestAverage)

8 Doing the Same Thing with Arrays (Example 8-4 on p. 514.)
Run it (weeok09Example8_4.cpp)

9 Making It More Flexible
The program on the previous slide assumes you have 5 test scores, and the number 5 is hard-coded into the code at several places. Better way: Declare a constant named ARRAY_SIZE at the program’s beginning, and use that constant wherever you need the array size. Then you only need to make one change instead of several if you have more than 5 test scores. See next slide…

10 Making It More Flexible (Improved version of Example 8-4 on p. 514.)
Run it (week09Example8_4Improved.cpp).

11 Array Dimension In a one-dimensional array, you can think of the elements as being arranged in a list. In a two-dimensional array, you can think of the elements as being arranged in a table with rows and columns. Higher-dimensional arrays are also possible, but we’ll focus on one-dimensional arrays this week, and two-dimensional arrays next week . C++ Programming: From Problem Analysis to Program Design, Seventh Edition

12 The Importance of Arrays to Engineers
Many engineering problems require you to manipulate vectors and matrices, which you’ve probably studied in a math or physics class. In C++, vectors are called one-dimensional arrays, and matrices are called two-dimensional arrays. The software named MATLAB, which most engineers are expected to learn, uses vectors and matrices extensively. Many concepts that you learn about arrays in C++ will carry over into MATLAB, and vice versa.

13 Declaring a 1-D Array Examples:
Syntax for declaring a one-dimensional array: where intExp is any constant expression that evaluates to a positive integer, and dataType is the type of the elements. Examples: int test[5]; double myArray1[100]; char myArray2[7000]; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

14 Accessing Array Elements
Syntax for accessing an array element: where indexExp is called the index. It’s an expression with a nonnegative integer value. The value of the index is the position of the element in the array. [] is called the array subscripting operator. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

15 Indexes Start at 0, Not at 1 The value of the index is the element’s position in the array. The array’s first element has index 0. The array’s second element has index 1. And so on. Forgetting this leads to a common type of error called an off-by-one error. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

16 Accessing Array Elements (cont’d.)
C++ Programming: From Problem Analysis to Program Design, Seventh Edition

17 Accessing Array Elements (cont’d.)
Do practice question 1. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

18 Array Initialization During Declaration
Arrays can be initialized during declaration. Values are placed between curly braces. If no array size is given inside the square brackets, the array’s size is determined by the number of initial values in the braces. Example: Here we declare and initialize an array of type double with four elements: double sales[] = {12.25, 32.50, 16.90, 45.68}; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

19 Partial Initialization of Arrays During Declaration
If you specify an array size in square brackets but only give initial values for some of the elements, the remaining elements are initialized to 0. Example: int list[10] = {8, 5, 12}; Declares an array of 10 elements and initializes list[0] to 8, list[1] to 5, list[2] to 12. All other elements are initialized to 0. Do practice question 2. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

20 Processing One-Dimensional Arrays
Some basic operations on a 1-D array: Initializing the array Inputting data into the array from the keyboard Displaying data stored in the array Copying the array into another array Finding the largest and/or smallest element in the array Each operation requires you to step through the array’s elements one by one. This is easily accomplished using a loop. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

21 No Aggregate Operations on Arrays
An aggregate operation is an operation (such as assignment, input, output, etc.) that treats the entire array as a single unit. C++ does not allow aggregate operations on arrays. Example: C++ Programming: From Problem Analysis to Program Design, Seventh Edition

22 Example: Initializing a One-Dimensional Array
Given the declaration: int list[100]; //array of size 100 Use a for loop to initialize all array elements to some value (13 in this case): for (int i = 0; i < 100; i++) list[i] = 13; The following aggregate operation is illegal: list = 13; //Error!!! We execute this statement 100 times, but each time i has a different value, so each time we access a different array element. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

23 Example: Inputting Values into a One-Dimensional Array from the Keyboard
Given the declaration: int list[100]; //array of size 100 Use a for loop to input all values from the keyboard: for (int i = 0; i < 100; i++) cin >> list[i]; The following aggregate operation is illegal: cin >> list; //Error!!! C++ Programming: From Problem Analysis to Program Design, Seventh Edition

24 Example: Displaying Values Stored in a One-Dimensional Array
Given the declaration: int list[100] = {0}; //array of size 100 Use a for loop to display all values: for (int i = 0; i < 100; i++) cout << list[i] << endl; The following aggregate operation is illegal: cout << list << endl; //Error!!! C++ Programming: From Problem Analysis to Program Design, Seventh Edition

25 Example: Copying a One-Dimensional Array into Another Array
Given the declaration: int myList[100] = {0}; //array of size 100 int yourList[100]; //array of size 100 Use a for loop to copy all values: for (int i = 0; i < 100; i++) yourList[i] = myList[i]; The following aggregate operation is illegal: yourList = mylist; //Error!!! Do practice question 3. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

26 Array Index Out of Bounds
An array’s index is in bounds if the index is >=0 and <= the array’s size minus 1. Otherwise, the index is out of bounds. C++ does not guard against indices that are out of bounds. You (the programmer) must insure that you never use out-of-bounds indices. Otherwise your program may fail. The next three slides show three examples that fail in different ways. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

27 Array Index Out of Bounds: Example 1
Run it (week09ArrayIndexOutOfBounds1.cpp), and then single-step it. The compiler will not catch this error. It’s a logic error that will produce garbage results when you run the program.

28 Array Index Out of Bounds: Example 2
Run it week09ArrayIndexOutOfBounds2.cpp The compiler will not catch this error. It’s a run-time error that will crash your program when you run it.

29 Array Index Out of Bounds: Example 3
Run it week09ArrayIndexOutOfBounds3.cpp The compiler will catch this error and refuse to run the program.

30 Arrays as Parameters to Functions
When used as function parameters, arrays are always passed by reference (never by value). But you do not use the symbol & when declaring an array as a formal parameter. Example: As shown here, we usually omit the array’s size in the parameter list. If you provide the size, the compiler ignores it. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

31 Example: Array as a Parameter to a Function
Do as practice question 4. -Then run it (week09ArrayParameter.cpp). Also note error if you put an & in the parameter list or if you put [] in the function call.

32 A Potential Problem with Passing Parameters by Reference
Whenever a parameter is passed by reference, the called function can change the value of the calling function’s variable. What if you don’t want this? With parameters of simple data types (int, double, etc.), you have the option of passing the parameter by value instead of by reference, thus preventing the called function from changing the calling function’s value. But with arrays, you don’t have this option. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

33 Solution to Potential Problem: Constant Formal Parameters
Solution: To prevent a called function from changing the value of the calling function’s variable when passing by reference, use const in the formal parameter list. Example: Within the function example, any attempt to change the values in y will result in an error. See next slide. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

34 Example: A Constant Parameter
Run it (week09ConstantParameter.cpp). Do practice question 5.

35 A Function Cannot Return an Array
C++ does not allow functions to return a value of type array. The code shown here won’t run. Run it (week09ReturnArray.cpp) and show that you can’t fix it by fiddling with the function’s return value. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

36 Base Address of an Array and Array in Computer Memory
An array’s base address is the address (memory location) of the array’s first element. Example: If list is a one-dimensional array, its base address is the address of list[0]. When an array is passed as a parameter, the base address of the actual array is passed to the formal parameter. Demo by single-stepping week09ArrayParameter.cpp. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

37 An Array’s Size Cannot Be a Variable
In most example programs above we have used an integer inside the [] when we declared an array. Example: int testScores[20]; You can use an integer constant instead. Example: const int NUMBER_OF_STUDENTS = 20; int testScores1[NUMBER_OF_STUDENTS]; But you cannot use an integer variable. Example: int numberOfStudents = 20; int testScores2[numberOfStudents]; //ERROR! Demo with week09DeclarationError.cpp. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

38 An Array’s Size Cannot Be a Variable (cont’d.)
This is a serious limitation because it prevents you from letting the user choose the size of an array. Example: int numberOfStudents; cout << "How many students?" << endl; cin >> numberOfStudents; int testScores2[numberOfStudents]; //ERROR! C++ provides a way to get around this limitation, but it requires you to use pointers, which we won’t look at until later in the course. If you’re interested, look ahead to the section in Chapter 12 called “Dynamic Arrays”. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

39 Parallel Arrays We say two (or more) arrays are parallel if their corresponding elements hold related information. Example: int studentId[50]; char courseGrade[50]; C++ does not “know” that these two arrays have anything to do with each other. They are parallel only in the programmer’s mind. Do practice question 6. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

40 Review: Two Kinds of Strings in C++
In C++, the term “string” can mean: The string data type, which is new to C++. (It did not exist in C.) To use it, you must include the <string> header file. We’ve been using this data type since Week 2. Discussed in Chapter 7. A null-terminated character array. This was the only kind of string in C. The book refers to these as “C-strings.” Much less convenient than C++’s string data type. Discussed in Chapter 8, but we won’t use it. The many powerful string-handling functions that we looked at last week work on the string data type but not on C-strings.

41 A Brief Look at C-Strings
A character array is an array whose elements are of type char. A C-string is a special type of character array: it is a null-terminated character array, which means that it ends with the null character. The null character is the character whose ASCII code is 0. To type it in a program, you type '\0'. Example: char name[10] = “John”; C++ Programming: From Problem Analysis to Program Design, Seventh Edition

42 Searching and Sorting Arrays
Two classic computer-science problems that have been studied exhaustively over the past six decades are: How to search an array to see whether it contains a given value. How to sort the elements in an array (for example, from smallest to largest in an integer array). The next slides show two primitive solutions to these problems. Chapter 16 (which we won’t study) goes into much more detail.

43 One Method for Searching an Array: Sequential Search
To search an array for a given item using a sequential search (or linear search): Start from the first array element. Compare each element in the array with the value being searched for. Continue until the item is found or you’ve reached the end of the array. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

44 One Method for Sorting an Array: Selection Sort
To sort an array using a selection sort: rearrange the list by selecting an element and moving it to its proper position. Steps: Find the smallest element in the unsorted portion of the list. Move it to the top of the unsorted portion by swapping it with the element currently there. Start again with the rest of the list. C++ Programming: From Problem Analysis to Program Design, Seventh Edition

45 Selection Sort: Example
Walk through the process for Step (a), which is similar to what they have to do for the two lab programs where they find smallest and largest value in the array. -Do practice question 7. C++ Programming: From Problem Analysis to Program Design, Seventh Edition


Download ppt "EGR 2261 Unit 9 One-dimensional Arrays"

Similar presentations


Ads by Google