Chapter 7: Arrays.

Slides:



Advertisements
Similar presentations
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.
Advertisements

©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Multiple-Subscripted Array
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 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
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.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C-Strings, Arrays, and String Class Review.
Lecture: Arrays. 7.1 Arrays Hold Multiple Values.
Defining a 2d Array A 2d array implements a MATRIX. Example: #define NUMROWS 5 #define NUMCOLS 10 int arr[NUMROWS][NUMCOLS];
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
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.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by.
+ Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda.
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.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
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 © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays Starting Out with C++ Early Objects Seventh Edition by.
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.
CSCI 161 Lecture 14 Martin van Bommel. New Structure Recall “average.cpp” program –Read in a list of numbers –Count them and sum them up –Calculate the.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
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.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
ARRAYS (C) KHAERONI, M.SI. OVERVIEW Introduction to Arrays Arrays in Functions Programming with Arrays Multidimensional Arrays.
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
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Alternate Version of Starting Out with C++, Third Edition
Chapter 7: Arrays.
Lecture 6 Arrays and Vectors
Computer Science 210 Computer Organization
Chapter 7: Arrays.
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Chapter 9: Pointers.
Chapter 7 – Arrays.
Lecture 3 C & C++ programming.
Week 13 & 14 Arrays SCK1213Programming Technique I SEM1 2009/2010
Array An “average.cpp” program
New Structure Recall “average.cpp” program
Multi-dimensional Array
Pointer.
7 Chapter Arrays.
Chapter 8: Arrays Starting Out with C++ Early Objects Eighth Edition
Computer Science 210 Computer Organization
Chapter 9: Pointers.
Engineering Problem Solving with C++, Etter/Ingber
7 Arrays.
Standard Version of Starting Out with C++, 4th Edition
Review for Final Exam.
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
Arrays Arrays A few types Structures of related data items
Arrays An array is a grouping of elements of the same type that share a common base name Can have any number of elements in the array Individual elements.
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Presentation transcript:

Chapter 7: Arrays

Arrays Hold Multiple Values 7.1 Arrays Hold Multiple Values

Array - Memory Layout The definition: allocates the following memory: int tests[5]; allocates the following memory: first element second element 1 third element 2 fourth element 3 fifth element 4

Size Declarators Named constants are commonly used as size declarators. const int SIZE = 5; int tests[SIZE]; This eases program maintenance when the size of the array needs to be changed.

Accessing Array Contents Can access element with a constant or literal subscript: cout << tests[3] << endl; Can use integer expression as subscript: int i = 5; cout << tests[i] << endl;

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;

7.4 Array Initialization

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.

Code From Program 7-6

Printing the Contents of an Array You can display the contents of a character array by sending its name to cout: char fName[] = "Henry"; cout << fName << endl; But, this ONLY works with character arrays! For other types of arrays, you must print element-by-element: for (i = 0; i < ARRAY_SIZE; i++) cout << tests[i] << endl;

Comparing Arrays To compare two arrays, you must compare element-by-element: const int SIZE = 5; int firstArray[SIZE] = { 5, 10, 15, 20, 25 }; int secondArray[SIZE] = { 5, 10, 15, 20, 25 }; bool arraysEqual = true; // Flag variable int count = 0; // Loop counter variable // Compare the two arrays. while (arraysEqual && count < SIZE) { if (firstArray[count] != secondArray[count]) arraysEqual = false; count++; } if (arraysEqual) cout << "The arrays are equal.\n"; else cout << "The arrays are not equal.\n";

7.7 Using Parallel Arrays

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

Parallel Array Example const int SIZE = 5; // Array size int id[SIZE]; // student ID double average[SIZE]; // course average char grade[SIZE]; // course grade ... for(int i = 0; i < SIZE; i++) { cout << "Student ID: " << id[i] << " average: " << average[i] << " grade: " << grade[i] << endl; }

Parallel Arrays in Program 7-15 (Program Continues)

Parallel Arrays in Program 7-15

Parallel Arrays in Program 7-15 The hours and payRate arrays are related through their subscripts:

Arrays as Function Arguments 7.8 Arrays as Function Arguments

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

Passing an Array to a Function in Program 7-17 (Program Continues)

Passing an Array to a Function in Program 7-17

Modifying Arrays in Functions Array names in functions are like reference variables – changes made to array in a function are reflected in actual array in calling function

Mechanics of Array Parameters When variable used as parameter, only its value is passed When array name used as parameter, only base address of array sent to function Function can then operate on the array in place without copying its contents Storage for parameter array is shared with actual argument array

Function Prototypes void PrintIntArray(int array[], int n); void ReverseIntArray(int array[], int n);

GetIntArray Prototype GetIntArray has different structure Do not know the effective size before call GetIntArray determines effective size Needs to know actual size to limit it Also give it sentinel value for flexibility int GetIntArray(int array[], int max, int sentinel); The function returns the actual size of the array

Implementing PrintIntegerArray void PrintIntArray(int array[], int n) { int i; for (i = 0; i < n; i++) cout << array[i] << endl; }

int GetIntArray(int array[], int max, int sentinel) { int n = 0, value; cout << ” ? ”; cin >> value; while (value != sentinel) { if (n >= max) cout << ”Too many items”; else array[n] = value; n++; } return n;

ReverseIntArray void ReverseIntArray(int array[], int n) { int i, limit; limit = n / 2; for (i = 0; i < limit; i++) { Swap values in array[i] and array[n-i-1] }

Swap Array Elements Try No, because passing values in array Can use Swap(array[i], array[n-i-1]); No, because passing values in array Can use Swap(array, i, n-i-1);

SwapIntElements void SwapIntElements(int array[], int p1, int p2) { int tmp = array[p1]; array[p1] = array[p2]; array[p2] = tmp; }

Two-Dimensional Arrays 7.9 Two-Dimensional Arrays

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

Two-Dimensional Array Representation const int ROWS = 4, COLS = 3; int exams[ROWS][COLS]; Use two subscripts to access element: exams[2][2] = 86; columns 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] r o w s

A Two-dimensional Array in Program 7-21

A Two-dimensional Array in Program 7-21

A Two-dimensional Array in Program 7-21

2D 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 84 78 92 97

Two-Dimensional Array as Parameter, Argument Use array name as argument in function call: getExams(exams, 2); Use empty [] for row, size declarator for column in prototype, header: const int COLS = 2; // Prototype void getExams(int [][COLS], int); // Header void getExams(int exams[][COLS], int rows)

Example – The showArray Function from Program 7-22

How showArray is Called

Summing All the Elements in a Two-Dimensional Array Given the following definitions: const int NUM_ROWS = 5; // Number of rows const int NUM_COLS = 5; // Number of columns int total = 0; // Accumulator int numbers[NUM_ROWS][NUM_COLS] = {{2, 7, 9, 6, 4}, {6, 1, 8, 9, 4}, {4, 3, 7, 2, 9}, {9, 9, 0, 3, 1}, {6, 2, 7, 4, 1}};

Summing All the Elements in a Two-Dimensional Array // Sum the array elements. for (int row = 0; row < NUM_ROWS; row++) { for (int col = 0; col < NUM_COLS; col++) total += numbers[row][col]; } // Display the sum. cout << "The total is " << total << endl;

Summing the Rows 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}};

Summing the Rows of a Two-Dimensional Array // Get each student's average score. for (int row = 0; row < NUM_STUDENTS; row++) { // Set the accumulator. total = 0; // Sum a row. for (int col = 0; col < NUM_SCORES; col++) total += scores[row][col]; // Get the average average = total / NUM_SCORES; // Display the average. cout << "Score average for student " << (row + 1) << " is " << average <<endl; }

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}};

Summing the Columns of a Two-Dimensional Array // Get the class average for each score. for (int col = 0; col < NUM_SCORES; col++) { // Reset the accumulator. total = 0; // Sum a column for (int row = 0; row < NUM_STUDENTS; row++) total += scores[row][col]; // Get the average average = total / NUM_STUDENTS; // Display the class average. cout << "Class average for test " << (col + 1) << " is " << average << endl; }