Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Advertisements

Starting Out with C++, 3 rd Edition 1 Chapter 8 – Searching and Sorting Arrays.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 8 Arrays.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
C++ for Engineers and Scientists Third Edition
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
Lesson 7 Arrays CS 1 Lesson 7 -- John Cole1. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored.
Chapter 11 Structure. 2 Objectives You should be able to describe: Structures Arrays of Structures Structures as Function Arguments Dynamic Structure.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Chapter 11: Structured Data. Slide Introduction An array makes it possible to access a list or table of data of the same data type by using a single.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Searching and Sorting Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
Chapter Searching and Sorting Arrays 8. Introduction to Search Algorithms 8.1.
Lecture 16: Searching and Sorting Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
Arrays Chapter 8.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
1 Chapter 11 Structured Data. 2 Topics 10.1 Abstract Data Types 10.2 Combining Data into Structures 10.3 Accessing Structure Members 10.4 Initializing.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Lecture: Arrays. 7.1 Arrays Hold Multiple Values.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
Structured Data Chapter 11. Combining Data Into Structures Structure: C++ construct that allows multiple variables to be grouped together Format: struct.
A FIRST BOOK OF C++ CHAPTER 16 DATA STRUCTURES. OBJECTIVES In this chapter, you will learn about: Single Structures Arrays of Structures Structures as.
1 Chapter 7 Arrays. 2 Topics 7.1 Arrays Hold Multiple Values 7.2 Accessing Array Elements 7.3 No Bounds Checking in C Array Initialization 7.5 Processing.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 8 Arrays.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 8: Arrays by Tony.
Copyright 2003 Scott/Jones Publishing Alternate Version of Starting Out with C++, Third Edition Chapter 8 Arrays.
Lecture 14: Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Chapter 7 Arrays Csc 125 Introduction to C++. Topics Arrays Hold Multiple Values Array Operations Arrays as function arguments Two-dimensional arrays.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 7: Arrays.
Arrays Chapter 7. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1.
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
Copyright © 2012 Pearson Education, Inc. Chapter 7: Arrays.
1 1  Lecture 11 – Structured Data FTMK, UTeM – Sem /2014.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
ARRAYS (C) KHAERONI, M.SI. OVERVIEW Introduction to Arrays Arrays in Functions Programming with Arrays Multidimensional Arrays.
Chapter Structured Data 11. Combining Data into Structures 11.2.
Chapter 7: Arrays. 7.1 Arrays Hold Multiple Values.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays Hold Multiple Values 7.1.
Lecture 2 Arrays. Topics 1 Arrays hold Multiple Values 2 Accessing Array Elements 3 Inputting and Displaying Array Contents 4 Array Initialization 5 Using.
Chapter 8: Arrays. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Objectives You should be able to describe: One-Dimensional Arrays
Searching and Sorting Arrays
Searching and Sorting Arrays
Chapter 7: Arrays.
Lecture 6 Arrays and Vectors
11 Chapter Structured Data
Chapter 7: Arrays.
Chapter 11: Structured Data.
Sorting Algorithms.
New Structure Recall “average.cpp” program
Chapter 7: Arrays.
7 Chapter Arrays.
Chapter 11: Structured Data.
Standard Version of Starting Out with C++, 4th Edition
Searching and Sorting Arrays
Standard Version of Starting Out with C++, 4th Edition
Presentation transcript:

Chapter 7: Arrays

Outline Array Definition Access Array Array Initialization Array Processing 2D Array

Slide 7- 3 Array Terminology The above definition allocates the following memory: first element second element third element fourth element fifth element

Slide 7- 4 Array Terminology The size of an array is: – the total number of bytes allocated for it – (number of elements) * (number of bytes for each element) Examples: int tests[5] is an array of 20 bytes, assuming 4 bytes for an int long double measures[10] is an array of 80 bytes, assuming 8 bytes for a long double

Slide 7- 5 Accessing Array Elements Each element in an array is assigned a unique subscript. Subscripts start at 0 The last element’s subscript is n-1 where n is the number of elements in the array subscripts:

Slide 7- 6 Accessing Array Elements Array elements can be used as regular variables: tests[0] = 79; cout << tests[0]; cin >> tests[1]; tests[4] = tests[0] + tests[1]; Arrays must be accessed via individual elements: cout << tests; // not legal!!

Slide 7- 7 Using a Loop to Step Through an Array Example – The following code defines an array, numbers, and assigns 99 to each element: const int ARRAY_SIZE = 5; int numbers[ARRAY_SIZE]; for (int count = 0; count < ARRAY_SIZE; count++) numbers[count] = 99;

Slide 7- 8 A Closer Look At the Loop

Slide 7- 9 Off-By-One Errors An off-by-one error happens when you use array subscripts that are off by one. This can happen when you start subscripts at 1 rather than 0: // This code has an off-by-one error. const int SIZE = 100; int numbers[SIZE]; for (int count = 1; count <= SIZE; count++) numbers[count] = 0;//two mistakes

Slide Array Initialization Arrays can be initialized with an initialization list: const int SIZE = 5; int tests[SIZE] = {79,82,91,77,84}; The values are stored in the array in the order in which they appear in the list. The initialization list cannot exceed the array size.

Slide Partial Array Initialization If array is initialized with fewer initial values than the size declarator, the remaining elements will be set to 0:

Character Arrays Character Arrays are different in various ways from numeric arrays. Declaring Character Arrays – Must always allow room for 1 extra element - the NULL (or: ’ \0’ ) – Example: //Implicit Array Sizing char name[] = "Joe Smith"; //What is sizeof(name); char name[] = {'J', 'o', 'e',' ','S', 'm', 'i', 't', 'h','\0'}; Slide 7- 12

Slide Summing and Averaging Array Elements Use a simple loop to add together array elements: int tnum; double average, sum = 0; for(tnum = 0; tnum < SIZE; tnum++) sum += tests[tnum]; Once summed, can compute average: average = sum / SIZE;

Slide Example 1: Find the highest score int count; int highest; highest = numbers[0]; for (count = 1; count < SIZE; count++) { if (numbers[count] > highest) highest = numbers[count]; } When this code is finished, the highest variable will contains the highest value in the numbers array.

Slide Using Parallel Arrays Parallel arrays: two or more arrays that contain related data A subscript is used to relate arrays: elements at same subscript are related Arrays may be of different types

Arrays as Function Arguments When passing an array to a function, it is common to pass array size so that function knows how many elements to process: showScores(tests, ARRAY_SIZE); Array size must also be reflected in prototype, header: void showScores(int [], int); // function prototype void showScores(int tests[], int size) // function header

#include using namespace std; void arrayfunc(int num[], int size) { for(int i=0; i<size; i++) { num[i]++; cout<<num[i]<<" "; } void main() { const int size=6; int aa[size] = {10,20,30,40,50,60}; for(int i=0; i<size; i++) cout<<aa[i]<<" "; cout<<"\n"; arrayfunc(aa, size); cout<<"\n"; for(int i=0; i<size; i++) cout<<aa[i]<<" "; cout<<"\n"; }

Outline Array Definition Access Array Array Initialization Array Processing 2D Array

Slide Two-Dimensional Arrays Can define one array for multiple sets of data Like a table in a spreadsheet Use two size declarators in definition: const int ROWS = 4, COLS = 3; int exams[ROWS][COLS]; First declarator is number of rows; second is number of columns

Slide Two-Dimensional Array Representation const int ROWS = 4, COLS = 3; int exams[ROWS][COLS]; Use two subscripts to access element: exams[2][2] = 86; Price = exams[2][1]; Newnum = 4*(exams[1][0]-5); sumRow = exams[0][0]+ exams[0][1]+ exams[0][2]; exams[0][0]exams[0][1]exams[0][2] exams[1][0]exams[1][1]exams[1][2] exams[2][0]exams[2][1]exams[2][2] exams[3][0]exams[3][1]exams[3][2] columns rowsrows

Slide D Array Initialization Two-dimensional arrays are initialized row-by- row: const int ROWS = 2, COLS = 2; int exams[ROWS][COLS] = { {84, 78},{92, 97} }; Can omit inner { }, some initial values in a row – array elements without initial values will be set to 0 or NULL

Slide Summing the Columns of a Two-Dimensional Array Given the following definitions: const int NUM_STUDENTS = 3; const int NUM_SCORES = 5; double total; // Accumulator double average; // To hold average scores double scores[NUM_STUDENTS][NUM_SCORES] = {{88, 97, 79, 86, 94}, {86, 91, 78, 79, 84}, {82, 73, 77, 82, 89}};

Chapter 8: Searching and Sorting Arrays

Linear Search Also called the sequential search Starting at the first element, this algorithm sequentially steps through an array examining each element until it locates the value it is searching for.

Linear Search - Example Array numlist contains: Searching for the the value 11, linear search examines 17, 23, 5, and 11 Searching for the the value 7, linear search examines 17, 23, 5, 11, 2, 29, and

Linear Search Algorithm: set found to false; set position to –1; set index to 0 while index < number of elts. and found is false if list[index] is equal to search value found = true position = index end if add 1 to index end while return position

A Linear Search Function int searchList(int list[], int numElems, int value) { int index = 0; // Used as a subscript to search array int position = -1; // To record position of search value bool found = false; // Flag to indicate if value was found while (index < numElems && !found) { if (list[index] == value) // If the value is found { found = true; // Set the flag position = index; // Record the value's subscript } index++; // Go to the next element } return position; // Return the position, or -1 }

Selection Sort Concept for sort in ascending order: – Locate smallest element in array. Exchange it with element in position 0 – Locate next smallest element in array. Exchange it with element in position 1. – Continue until all elements are arranged in order

Selection Sort - Example Array numlist contains: 1.Smallest element is 2. Exchange 2 with element in 1 st position in array:

Example (Continued) 2.Next smallest element is 3. Exchange 3 with element in 2 nd position in array: 3.Next smallest element is 11. Exchange 11 with element in 3 rd position in array:

A Selection Sort Function – From Program void selectionSort(int array[], int size) 36 { 37 int startScan, minIndex, minValue; for (startScan = 0; startScan < (size - 1); startScan++) 40 { 41 minIndex = startScan; 42 minValue = array[startScan]; 43 for(int index = startScan + 1; index < size; index++) 44 { 45 if (array[index] < minValue) 46 { 47 minValue = array[index]; 48 minIndex = index; 49 } 50 } 51 array[minIndex] = array[startScan]; 52 array[startScan] = minValue; 53 } 54 }

Chapter 11: Structured Data

Slide Combining Data into Structures Structure: C++ construct that allows multiple variables to be grouped together General Format: struct { type1 field1; type2 field2;... };

Slide Example struct Declaration struct Student { int studentID; string name; short yearInSchool; double gpa; }; structure tag structure members

Slide Accessing Structure Members Use the dot (.) operator to refer to members of struct variables: cin >> bill.studentID; getline(cin, bill.name); bill.gpa = 3.75; Member variables can be used in any manner appropriate for their data type

Slide Displaying a struct Variable To display the contents of a struct variable, must display each field separately, using the dot operator: cout << bill; // won’t work cout << bill.studentID << endl; cout << bill.name << endl; cout << bill.yearInSchool; cout << " " << bill.gpa;

Slide Comparing struct Variables Cannot compare struct variables directly: if (bill == william) // won’t work Instead, must compare on a field basis: if (bill.studentID == william.studentID)...

Slide Initializing a Structure struct variable can be initialized when defined: Student s = {11465, "Joan", 2, 3.75}; Can also be initialized member-by-member after definition: s.name = "Joan"; s.gpa = 3.75;

Slide Nested Structures A structure can contain another structure as a member: To include a structure within a structure (Nested Structures, p. 642), we follow the same rules for including any data type in a structure. For example, assume that a structure is to consist of a name and a date of birth, where a Date structure, has been declared as struct Date { int month; int day; int year; }; A suitable definition of a structure that includes a name and a Date structure is struct Person { string name; Date birth; };

struct Date { int month; int day; int year; }; struct Person { string name; Date birth; }; int main ( void ) { Person employee; employee.name = "Mary Hill"; employee.birth.month = 12; employee.birth.day = 25; employee.birth.year = 2002; cout << employee.name << " birthdate is: “ << employee.birth.month << "/" << employee.birth.day << "/“ << employee.birth.year; return 0; }

Slide Arrays of Structures Structures can be defined in arrays Can be used in place of parallel arrays const int NUM_STUDENTS = 20; Student stuList[NUM_STUDENTS]; Individual structures accessible using subscript notation Fields within structures accessible using dot notation: cout << stuList[5].studentID;

Slide Structures as Function Arguments Individual structure members may be passed to a function in the same manner as any variable. May pass members of struct variables to functions: computeGPA(stu.gpa); May pass entire struct variables to functions: showData(stu); Can use reference parameter if function needs to modify contents of structure variable

Slide Structures as Function Arguments Individual structure members may be passed to a function in the same manner as any variable. May pass members of struct variables to functions: computeGPA(stu.gpa); May pass entire struct variables to functions: showData(stu); Can use reference parameter if function needs to modify contents of structure variable

struct Employee // declare a global type { int id_number; double pay_rate; double hours; }; double calcNet(double, double); // function prototype int main ( void ) { Employee emp = {6782, 8.93, 40.5}; double net_pay; net_pay = calcNet(emp.pay_rate, emp.hours); //PASS BY VALUE cout << setw(10) << fixed << showpoint << setprecision(2); cout << "The net pay for employee " << emp.id_number << " is $" << net_pay << endl; return 0; } double calcNet(double pay_rate, double hours) { return (pay_rate * hours); } //PASS BY VALUE //Output: The net pay for employee 6782 is $ This example passes copies of the values stored in structure members emp.pay_rate and emp.hours to the function named calcNet( ).

struct Employee // declare a global type { int id_number; double pay_rate; double hours; }; double calcNet(Employee); // function prototype int main ( void ) { Employee emp = {6782, 8.93, 40.5}; double net_pay; net_pay = calcNet(emp); cout << setw(10) << fixed <<showpoint << setprecision(2); cout << "The net pay for employee " << emp.id_number << " is $" << net_pay << endl; return 0; } double calcNet(Employee temp) {return (temp.pay_rate * temp.hours); } Output The net pay for employee 6782 is $361.66

Slide Returning a Structure from a Function - Example Student getStudentData() { Student tempStu; cin >> tempStu.studentID; getline(cin, tempStu.pData.name); getline(cin, tempStu.pData.address); getline(cin, tempStu.pData.city); cin >> tempStu.yearInSchool; cin >> tempStu.gpa; return tempStu; }