EGR 2261 Unit 9 One-dimensional Arrays

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
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 9: Arrays and Strings
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Chapter 9: Arrays and Strings
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.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Chapter 8 Arrays and Strings
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
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 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.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
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.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
Slide 1 Chapter 5 Arrays. Slide 2 Learning Objectives  Introduction to Arrays  Declaring and referencing arrays  For-loops and arrays  Arrays in memory.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Review for Final Exam. Contents 5 questions (20 points each) + 1 bonus question (20 points) – Basic concepts in Chapters 1-4 – Chapters 5-9 – Bonus: Chapter.
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.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Opening Input/Output Files ifstream infile; ofstream outfile; char inFileName[40]; char outFileName[40]; coutinFileName;
CPS120 Introduction to Computer Science Exam Review Lecture 18.
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.
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.
EGR 2261 Unit 13 Classes Read Malik, Chapter 10.
EGR 2261 Unit 11 Pointers and Dynamic Variables
User-Written Functions
EGR 2261 Unit 10 Two-dimensional Arrays
An Introduction to Programming with C++ Sixth Edition
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
Chapter 6 Arrays Lecturer: Mrs Rohani Hassan
EGR 2261 Unit 4 Control Structures I: Selection
Chapter 7 Part 1 Edited by JJ Shepherd
Arrays, For loop While loop Do while loop
Arrays and Strings Chapter 9.
CS 2308 Exam I Review.
7 Arrays.
Pointers, Dynamic Data, and Reference Types
Arrays Kingdom of Saudi Arabia
EKT150 : Computer Programming
Review for Final Exam.
EGR 2261 Unit 12 structs Read Malik, Chapter 9.
Review of Everything Arrays
Review for Final Exam.
7 Arrays.
Arrays Arrays A few types Structures of related data items
C++ Array 1.
Pointers, Dynamic Data, and Reference Types
Dr. Khizar Hayat Associate Prof. of Computer Science
4.1 Introduction Arrays A few types Structures of related data items
Presentation transcript:

EGR 2261 Unit 9 One-dimensional Arrays Read Malik, pages 519-549 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.

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

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

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

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

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

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)

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

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…

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

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

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.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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.

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

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

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.

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

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

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

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

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

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

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

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

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.

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

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.

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

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

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