starting out with c++, 3 rd edition 1 chapter 7 – arrays

111
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Upload: franklin-ramsey

Post on 13-Jan-2016

220 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

1

Chapter 7 – Arrays

Page 2: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

2

7.1 Arrays Hold Multiple values

• Unlike regular variables, arrays can hold multiple values.

Page 3: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

3

Figure 7-1

int count Enough memory for 1 int

12345

float price Enough memory for 1 float

56.981

char letter Enough memory for 1 char

A

Page 4: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

4

Figure 7-2

Page 5: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

5

Table 7-1

Array Declaration Number of Elements

Size of Each Element

Size of the Array

char letters[25]; 25 1 byte 25 bytes short rings[100]; 100 2 bytes 200 bytes int miles[84]; 84 4 bytes 336 bytes float temp[12]; 12 4 bytes 48 bytes doubledDistance[1000]; 1000 8 bytes 8000 bytes

Page 6: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

6

7.2 Accessing Array elements

• The individual elements of an array are assigned unique subscripts. These subscripts are used to access the elements.

Page 7: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

7

Program 7-1// This program asks the user for the number of hours worked// by 6 employees. It uses a 6-element int array to store the// values.

#include <iostream.h>

void main(void){

short hours[6];

cout << "Enter the hours worked by six employees: ";cin >> hours[0];cin >> hours[1];cin >> hours[2];cin >> hours[3];

Page 8: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

8

Program continuescin >> hours[4];cin >> hours[5];cout << "The hours you entered are:";cout << " " << hours[0];cout << " " << hours[1];cout << " " << hours[2];cout << " " << hours[3];cout << " " << hours[4];cout << " " << hours[5] << endl;

}

Page 9: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

9

Program Output with Example Input

Enter the hours worked by six employees: 20 12 40 30 30 15 [Enter]

The hours you entered are: 20 12 40 30 30 15

Page 10: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

10

Figure 7-7

Page 11: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

11

Program 7-2// This program asks the user for the number of hours worked// by 6 employees. It uses a 6-element short array to store the// values. #include <iostream.h>

void main(void){

short hours[6];

cout << "Enter the hours worked by six employees: ";for (int count = 0; count < 6; count++)

cin >> hours[count];cout << "The hours you entered are:";for (count = 0; count < 6; count++)

cout << " " << hours[count];cout << endl;

}

Page 12: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

12

Program Output with Example Input

Enter the hours worked by six employees: 20 12 40 30 30 15 [Enter]

The hours you entered are: 20 12 40 30 30 15

Page 13: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

13

Program 7-3// This program asks the user for the number of hours worked// by 6 employees. It uses a 6-element short array to store the// values.#include<iostream.h>

void main(void){

short hours[6];

cout << "Enter the hours worked by six employees.\n";for (int count = 1; count <= 6; count++){

cout << "Employee " << count << ": ";cin >> hours[count - 1];

}cout << "The hours you entered are\n";

Page 14: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

14

Program continues

for (count = 1; count <= 6; count++){

cout << "Employee " << count << ": ";cout << hours[count - 1] << endl;

}

}

Page 15: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

15

Program Output with Example InputEnter the hours worked by six employees.Employee 1: 20 [Enter]Employee 2: 12 [Enter]Employee 3: 40 [Enter]Employee 4: 30 [Enter]Employee 5: 30 [Enter]Employee 6: 15 [Enter]The hours you entered areEmployee 1: 20Employee 2: 12Employee 3: 40Employee 4: 30Employee 5: 30Employee 6: 15

Page 16: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

16

7.3 No Bounds Checking in C++

• C++ gives you the freedom to store data past an array’s boundaries.

Page 17: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

17

Program 7-4// This program unsafely accesses an area of memory by writing// values beyond an array's boundary.// WARNING: If you compile and run this program, it could cause// the computer to crash.#include <iostream.h>

void main(void){

short values[3]; // An array of 3 short integers.

cout << "I will store 5 numbers in a 3 element array!\n";for (int count = 0; count < 5; count++)

values[count] = 100;cout << "If you see this message, it means the computer\n";cout << "has not crashed! Here are the numbers:\n";for (int count = 0; count < 5; count++)

cout << values[count] << endl;

}

Page 18: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

18

Figure 7-8

Page 19: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

19

7.4 Array Initialization

• Arrays may be initialized when they are declared.

Page 20: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

20

Program 7-5

// This program displays the number of days in each month.// It uses a 12-element int array.

#include <iostream.h>

void main(void){

int days[12];days[0] = 31; // Januarydays[1] = 28; // Februarydays[2] = 31; // Marchdays[3] = 30; // Aprildays[4] = 31; // Maydays[5] = 30; // Junedays[6] = 31; // July

Page 21: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

21

Program continues

days[7] = 31; // Augustdays[8] = 30; // Septemberdays[9] = 31; // Octoberdays[10] = 30; // Novemberdays[11] = 31; // Decemberfor (int count = 0; count < 12; count++){

cout << "Month " << (count + 1) << " has ";

cout << days[count] << " days.\n";}

}

Page 22: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

22

Program Output

Month 1 has 31 days.Month 2 has 28 days.Month 3 has 31 days.Month 4 has 30 days.Month 5 has 31 days.Month 6 has 30 days.Month 7 has 31 days.Month 8 has 31 days.Month 9 has 30 days.Month 10 has 31 days.Month 11 has 30 days.Month 12 has 31 days.

Page 23: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

23

Program 7-6// This program displays the number of days in each month.// It uses a 12-element int array.#include <iostream.h>

void main(void){

int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};for (int count = 0; count < 12; count++){

cout << "Month " << (count + 1) << " has ";cout << days[count] << " days.\n";

}}

Page 24: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

24

Program Output

Month 1 has 31 days.Month 2 has 28 days.Month 3 has 31 days.Month 4 has 30 days.Month 5 has 31 days.Month 6 has 30 days.Month 7 has 31 days.Month 8 has 31 days.Month 9 has 30 days.Month 10 has 31 days.Month 11 has 30 days.Month 12 has 31 days.

Page 25: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

25

Program 7-7// This program uses an array of ten characters to store the// first ten letters of the alphabet. The ASCII codes of the// characters are displayed.#include <iostream.h>

void main(void){

char letters[10] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'};

cout << "Character" << "\t" << "ASCII Code\n";cout << "--------" << "\t" << "----------\n";for (int count = 0; count < 10; count++){

cout << letters[count] << "\t\t";cout << int(letters[count]) << endl;

}}

Page 26: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

26

Program Output

Character ASCII Code--------- ----------

A 65B 66C 67D 68E 69F 70G 71H 72I 73

J 74

Page 27: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

27

Partial Array Initialization

• When an array is being initialized, C++ does not require a value for every element.

int numbers[7] = {1, 2, 4, 8};

Page 28: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

28

Program 7-8// This program has a partially initialized array.

#include <iostream.h>

void main(void){

int numbers[7] = {1, 2, 4, 8}; // Initialize the // first 4 elements.

cout << "Here are the contents of the array:\n";for (int index = 0; index < 7; index++)

cout << numbers[index] << endl;}

Page 29: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

29

Program Output

Here are the contents of the array:1248000

Page 30: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

30

Implicit Array Sizing

• It is possible to declare an array without specifying its size, as long as you provide an initialization list.

float ratings[] = {1.0, 1.5, 2.0, 2.5, 3.0};

Page 31: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

31

Initializing With Strings

• When initializing a character array with a string, simply enclose the string in quotation marks:

char name[] = “Warren”;

Page 32: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

32

Figure 7-11

Page 33: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

33

Program 7-9// This program displays the contents of two char arrays.#include <iostream.h>

void main(void){

char name1[] = "Holly";char name2[] = {'W', 'a', 'r', 'r', 'e', 'n', '\0'};

cout << name1 << endl;cout << name2 << endl;

}

Page 34: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

34

Program Output

HollyWarren

Page 35: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

35

7.5 Processing Array Contents

• Individual array elements are processed like any other type of variable.

Page 36: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

36

Program 7-10// This program stores, in an array, the hours worked by 5// employees who all make the same hourly wage.

#include <iostream.h>

void main(void){

int hours[5];float payRate;

cout << "Enter the hours worked by 5 employees who all\n";cout << "earn the same hourly rate.\n";for (int index = 0; index < 5; index++){

cout << "Employee #" << (index + 1) << ": ";cin >> hours[index];

}

Page 37: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

37

Program continues

cout << "Enter the hourly pay rate for all the employees: ";cin >> payRate;cout << "Here is the gross pay for each employee:\n";cout.precision(2);cout.setf(ios::fixed | ios::showpoint);for (index = 0; index < 5; index++){

float grossPay = hours[index] * payRate;cout << "Employee #" << (index + 1);cout << ": $" << grossPay << endl;

}}

Page 38: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

38

Program Output with Example InputEnter the hours worked by 5 employees who allearn the same hourly rate.Employee #1: 5 [Enter]Employee #2: 10 [Enter]Employee #3: 15 [Enter]Employee #4: 20 [Enter]Employee #5: 40 [Enter]Enter the hourly pay rate for all the employees: 12.75

[Enter]Here is the gross pay for each employee:Employee #1: $63.75Employee #2: $127.50Employee #3: $191.25Employee #4: $255.00Employee #5: $510.00

Page 39: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

39

Program 7-11// This program stores, in an array, the hours worked by 5// employees who all make the same hourly wage. It then// displays the gross pay, including any overtime.

#include <iostream.h>

// Constant for defining the array size

void main(void){

int hours[5];float payRate;

cout << "Enter the hours worked by 5 employees who all\n";cout << "earn the same hourly rate.\n";for (int index = 0; index < 5; index++){

cout << "Employee #" << (index + 1) << ": ";cin >> hours[index];

}

Page 40: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

40

Program continuescout << "Enter the hourly pay rate for all the employees: ";cin >> payRate;cout << "Here is the gross pay for each employee:\n";cout.precision(2);cout.setf(ios::fixed | ios::showpoint);for (index = 0; index < 5; index++){

float grossPay, overTime;if (hours[index] > 40){

// Calculate pay for 40 hours.grossPay = 40 * payRate; // Calculate overtime pay.overTime = (hours[index] - 40) * 1.5 *

payRate;// Add regular pay and overtime pay.grossPay += overTime;

}

Page 41: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

41

Program continues

elsegrossPay = hours[index] * payRate;

cout << "Employee #" << (index + 1);cout << ": $" << grossPay << endl;

}}

Page 42: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

42

Program Output with Example InputEnter the hours worked by 5 employees who allearn the same hourly rate.Employee #1: 10 [Enter]Employee #2: 20 [Enter]Employee #3: 50 [Enter]Employee #4: 40 [Enter]Employee #5: 60 [Enter]

Enter the hourly pay rate for all the employees: 12.75 [Enter]

Here is the gross pay for each employee:Employee #1: $127.50Employee #2: $255.00Employee #3: $701.25Employee #4: $510.00Employee #5: $892.50

Page 43: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

43

7.6 Focus on Software Engineering: Parallel Arrays

• By using he same subscript, you can build relationships between data stored in two or more arrays.

Page 44: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

44

Program 7-12// This program stores, in two arrays, the hours worked by 5// employees, and their hourly pay rates.#include <iostream.h>

// Constant for defining the array sizeconst int numEmps = 5;

void main(void){

int hours[numEmps];float payRate[numEmps];

cout << "Enter the hours worked by “ << numEmps << “ employees and their\n";

cout << "hourly rates.\n"; for (int index = 0; index < numEmps; index++){

cout << "hours worked by employee #" << (index + 1);cout << ": ";

Page 45: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

45

Program continues

cin >> hours[index];cout << "Hourly pay rate for employee #";cout << (index + 1) << ": ";cin >> payRate[index];

}cout << "Here is the gross pay for each employee:\n";cout.precision(2);cout.setf(ios::fixed | ios::showpoint);for (index = 0; index < numEmps; index++){

float grossPay = hours[index] * payRate[index];cout << "Employee #" << (index + 1);cout << ": $" << grossPay << endl;

}}

Page 46: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

46

Program Output with Example InputEnter the hours worked by 5 employees and their hourly

rates.hours worked by employee #1: 10 [Enter]Hourly pay rate for employee #1: 9.75 [Enter]hours worked by employee #2: 15 [Enter]Hourly pay rate for employee #2: 8.62 [Enter]hours worked by employee #3: 20 [Enter]Hourly pay rate for employee #3: 10.50 [Enter]hours worked by employee #4: 40 [Enter]Hourly pay rate for employee #4: 18.75 [Enter]hours worked by employee #5: 40 [Enter]Hourly pay rate for employee #5: 15.65 [Enter]

Here is the gross pay for each employee:Employee #1: $97.50Employee #2: $129.30Employee #3: $210.00

Page 47: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

47

7.7 Thou Shalt Not Assign

• You cannot use the assignment operator to copy one array’s contents to another.

for (int count=0; count < 4; count++)

newVal[count] = oldVal[count];

Page 48: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

48

Table 7-2

Expression Value

O ld V alues[0 ] 10 (Contents of Element 0 of O ld V alues)

O ld V alues[1 ] 100 (Contents of Element 1 of O ld V alues)

O ld V alues[2 ] 200 (Contents of Element 2 of O ld V alues)

O ld V alues[3 ] 300 (Contents of Element 3 of O ld V alues)

N ew V alues 8012 (Memory Address of N ew V alues)

O ld V alues 8024 (Memory Address of O ld V alues)

Page 49: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

49

7.8 Printing the Contents of an Array

• To display the contents of an array, you must use a loop to display the contents of each element.

int array[5] = { 10, 20, 30, 40, 50 };for (int count = 0; count < 5; count++)

cout << array[count] << endl;

Page 50: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

50

7.9 Arrays As Function Arguments

• To pass an array as an argument to a function, pass the name of the array.

Page 51: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

51

Program 7-13// This program demonstrates that an array element is passed// to a function like any other variable.#include <iostream.h>

void ShowValue(int); // Function prototype

void main(void){

int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};

for (int Cycle = 0; Cycle < 8; Cycle++)ShowValue(collection[Cycle]);

}

Page 52: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

52

Program continues

//************************************// Definition of function showValue. *// This function accepts an integer argument. *// The value of the argument is displayed. *//************************************void ShowValue(int Num){

cout << Num << " ";}

Page 53: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

53

Program Output

5 10 15 20 25 30 35 40

Page 54: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

54

Program 7-14// This program demonstrates an array being passed to a function.#include <iostream.h>

void showValues(int []); // Function prototype

void main(void){

int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};

showValues(collection); // Passing address of array collection}

//***********************************************// Definition of function showValues. *// This function accepts an array of 8 integers *// as its argument. The contents of the array *// is displayed. *//***********************************************void showValues(int nums[]){

for (int index = 0; index < 8; index++)cout << nums[index] << " ";

}

Page 55: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

55

Program Output

5 10 15 20 25 30 35 40

Page 56: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

56

Program 7-15// This program demonstrates an array being passed to a function.#include <iostream.h>

void showValues(int []); // Function prototype

void main(void){

int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40};int set2[8] = {2, 4, 6, 8, 10, 12, 14, 16};showValues(set1);cout << endl;showValues(set2);

}

//***********************************************// Definition of function showValues. *// This function accepts an array of 8 integers *// as its argument. The contents of the array *// is displayed. *//***********************************************void showValues(int nums[]){

for (int index = 0; index < 8; index++)cout << nums[index] << " ";

}

Page 57: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

57

Program Output

5 10 15 20 25 30 35 402 4 6 8 10 12 14 16

Page 58: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

58

Program 7-16// This program uses a function that can display the contents// of an integer array of any size.#include <iostream.h>

void showValues(int [], int); // Function prototype

void main(void){

int set1[8] = {5, 10, 15, 20, 25, 30, 35, 40};int set2[4] = {2, 4, 6, 8};int set3[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

showValues(set1, 8);cout << endl;showValues(set2, 4);cout << endl;showValues(set3, 12);

}

Page 59: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

59

Program continues

//***********************************************// Definition of function showValues. *// This function displays the contents of the *// array passed into nums. The value passed *// into elements is the number of elements in *// the nums array. *//***********************************************

void showValues(int nums[], int elements){

for (int index = 0; index < elements; index++)cout << nums[index] << " ";

}

Page 60: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

60

Program Output

5 10 15 20 25 30 35 402 4 6 81 2 3 4 5 6 7 8 9 10 11 12

Page 61: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

61

Program 7-17// This program uses a function that doubles the contents of// the elements within an array.#include <iostream.h>

void doubleArray(int [], int); // Function prototypeconst int arraySize = 12;

void main(void){

int set[arraySize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};cout << "The arrays values are:\n";for (int index = 0; index < arraySize; index++)

cout << set[index] << " ";cout << endl;doubleArray(set, arraySize);cout << "After calling doubleArray, the values are:\n";

Page 62: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

62

Program continuesfor (int index = 0; index < arraySize; index++)

cout << set[index] << " ";cout << endl;

}

//**************************************************// Definition of function doubleArray. *// This function doubles the value of each element *// in the array passed into nums. *// The value passed into size is the number of *// elements in the nums array. *//**************************************************void doubleArray(int nums[], int size){

for (int index = 0; index < size; index++)nums[index] *= 2;

}

Page 63: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

63

Program Output

The array values are:1 2 3 4 5 6 7 8 9 10 11 12After calling doubleArray, the values are:2 4 6 8 10 12 14 16 18 20 22 24

Page 64: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

64

7.10 Two-dimensional Arrays

• A two-dimensional array is like several identical arrays put together. It is useful for storing multiple sets of data.

Page 65: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

65

Program 7-18// This program demonstrates a two-dimensional array.

#include <iostream.h>

void main(void){

float sales[3][4]; // 2D array, 3 rows and 4 columns.float totalSales = 0; // To hold the total sales.int dir, qtr; // Loop counters.

Page 66: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

66

Program continuescout << "This program will calculate the total sales of\n";cout << "all the company's divisions.\n";cout << "Enter the following sales information:\n\n";

// Nested loops to fill the array with quarterly// sales figures for each division.for (div = 0; div < 3; div++){

for (qtr = 0; qtr < 4; qtr++){

cout << "Division " << (div + 1);cout << ", Quarter " << (qtr + 1) << ": $";cin >> sales[div][qtr];

}cout << endl; // Print blank line.

}

Page 67: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

67

Program continues

// Nested loops to add all the elements.for (div = 0; div < 3; div++)

for (qtr = 0; qtr < 4; qtr++)totalSales += sales[div][qtr];

cout.precision(2);cout.setf(ios::fixed | ios::showpoint);cout << "The total sales for the company are: $";cout << totalSales << endl;

}

Page 68: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

68

Program Output with Example InputThis program will calculate the total sales ofall the company's divisions.Enter the following sales information:

Division 1, Quarter 1: $31569.45 [Enter]Division 1, Quarter 2: $29654.23 [Enter]Division 1, Quarter 3: $32982.54 [Enter]Division 1, Quarter 4: $39651.21 [Enter]

Division 2, Quarter 1: $56321.02 [Enter]Division 2, Quarter 2: $54128.63 [Enter]Division 2, Quarter 3: $41235.85 [Enter]Division 2, Quarter 4: $54652.33 [Enter]

Page 69: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

69

Output continues

Division 3, Quarter 1: $29654.35 [Enter]Division 3, Quarter 2: $28963.32 [Enter]Division 3, Quarter 3: $25353.55 [Enter]Division 3, Quarter 4: $32615.88 [Enter]

The total sales for the company are: $456782.34

Page 70: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

70

Passing Two-dimensional Arrays to Functions

• When a two-dimensional array is passed to a function, the parameter type must contain a size declarator for the number of columns.

Page 71: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

71

7.11 Arrays of Strings

• A two-dimensional array of characters can be used as an array of C-strings.

Page 72: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

72

Program 7-20// This program displays the number of days in each month.// It uses a two-dimensional character array to hold the // names of the months and an int array to hold the number// of days.#include <iostream.h>

void main(void){

char months[12][10] = {"January", "February", "March", "April", "May", "June",

"July", "August", "September”, "October", "November","December"};int days[12] = { 31, 28, 31, 30,

31, 30, 31, 31, 30, 31, 30, 31};

for (int count = 0; count < 12; count++){

cout << months[count] << " has ";cout << days[count] << " days.\n";

}}

Page 73: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

73

Program 7-20 (continued)

Program OutputJanuary has 31 days.February has 28 days.March has 31 days.April has 30 days. May has 31 days. June has 30 days. July has 31 days.August has 31 days. September has 30 days. October has 31 days. November has 30 days.December has 31 days.

Page 74: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

74

Three Dimensional Arrays and Beyond

• C++ allows you to create arrays with virtually any number of dimensions.

• Here is an example of a three-dimensional array declaration:

float seat[3][5][8];

Page 75: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

75

7.14 Introduction to the STL vector

• The Standard Template Library (or STL) is a collection of data types and algorithms that you may use in your programs. These data types and algorithms are programmer-defined. They are not part of the C++ language, but were created in addition to the built-in data types.

Page 76: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

76

7.14 Introduction to the STL vector

• The data types that are defined in the STL are commonly called containers, because they store and organize data.

• There are two types of containers in the STL: sequence containers and associative containers.

• The vector data type is a sequence container.

Page 77: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

77

7.14 Introduction to the STL vector

• A vector is like an array in the following ways:– A vector holds a sequence of values, or

elements.– A vector stores its elements in contiguous

memory locations.– You can use the array subscript operator [] to

read the individual elements in the vector

Page 78: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

78

7.14 Introduction to the STL vector

• However, a vector offers several advantages over arrays. Here are just a few:– You do not have to declare the number of

elements that the vector will have. – If you add a value to a vector that is already

full, the vector will automatically increase its size to accommodate the new value.

– vectors can report the number of elements they contain.

Page 79: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

79

Declaring a vector

• To use vectors in your program, you must first #include the vector header file with the following statement:

#include <vector> 

Note: There is no .h at the end of the file name.

Page 80: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

80

Declaring a vector

• The next step is to include the following statement after your #include statements:

using namespace std; 

The STL uses namespaces to organize the names of its data types and algorithms.

Page 81: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

81

Declaring a vector

• Now you are ready to declare an actual vector object. Here is an example:

vector<int> numbers;

The statement above declares numbers as a vector of ints.

Page 82: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

82

Declaring a vector

• You can declare a starting size, if you prefer. Here is an example:

vector<int> numbers(10);

The statement above declares numbers as a vector of 10 ints.

Page 83: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

83

Other examples of vector Declarations

Declaration Format Description

vector<float> amounts; Declares amounts as an empty vector of floats.

vector<int> scores(15); Declares scores as a vector of 15 ints.

vector<char> letters(25, 'A'); Declares letters as a vector of 25 characters. Each element is initialized with 'A'.

vector<double> values2(values1); Declares values2 as a vector of doubles. All the elements of values1, which also a vector of doubles, are copied to value2.

Page 84: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

84

Storing and Retrieving Values in a vector

• To store a value in an element that already exists in a vector, you may use the array subscript operator [].

Page 85: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

85

Program 7-23// This program stores, in two vectors, the hours worked by 5// employees, and their hourly pay rates.#include <iostream.h>#include <vector> // Needed to declare vectorsusing namespace std;

void main(void){

vector<int> hours(5); // Declare a vector of 5 integersvector<float> payRate(5); // Declare a vector of 5 floats

 cout << "Enter the hours worked by 5 employees and their\n";cout << "hourly rates.\n";for (int index = 0; index < 5; index++){

cout << "Hours worked by employee #" << (index + 1);cout << ": ";cin >> hours[index];cout << "Hourly pay rate for employee #";cout << (index + 1) << ": ";cin >> payRate[index];

}

Page 86: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

86

Program 7-23 (continued)cout << "Here is the gross pay for each employee:\n";cout.precision(2);cout.setf(ios::fixed | ios::showpoint);for (index = 0; index < 5; index++){ float grossPay = hours[index] * payRate[index];

cout << "Employee #" << (index + 1);cout << ": $" << grossPay << endl;

}}

Page 87: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

87

Program 7-23 (continued)Program Output with Example Input Shown in Bold

Enter the hours worked by 5 employees and theirhourly rates.Hours worked by employee #1: 10 [Enter]Hourly pay rate for employee #1: 9.75 [Enter]Hours worked by employee #2: 15 [Enter]Hourly pay rate for employee #2: 8.62 [Enter]Hours worked by employee #3: 20 [Enter]Hourly pay rate for employee #3: 10.50 [Enter]Hours worked by employee #4: 40 [Enter]Hourly pay rate for employee #4: 18.75 [Enter]Hours worked by employee #5: 40 [Enter]Hourly pay rate for employee #5: 15.65 [Enter]Here is the gross pay for each employee:Employee #1: $97.50Employee #2: $129.30Employee #3: $210.00Employee #4: $750.00Employee #5: $626.00

Page 88: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

88

Using the push_back Member Function

• You cannot use the [] operator to access a vector element that does not exist.

• To store a value in a vector that does not have a starting size, or is already full, use the push_back member function. Here is an example:

numbers.push_back(25);

Page 89: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

89

Program 7-24// This program stores, in two vectors, the hours worked by a specified// number of employees, and their hourly pay rates.

#include <iostream.h>#include <vector> // Needed to declare vectorsusing namespace std;

void main(void){

vector<int> hours; // hours is an empty vectorvector<float> payRate; // payRate is an empty vectorint numEmployees; // The number of employees

cout << "How many employees do you have? ";cin >> numEmployees;cout << "Enter the hours worked by " << numEmployees;cout << " employees and their hourly rates.\n";

Page 90: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

90

Program 7-24 (continued)for (int index = 0; index < numEmployees; index++){

int tempHours; // To hold the number of hours enteredfloat tempRate; // To hold the payrate entered

cout << "Hours worked by employee #" << (index + 1);cout << ": ";cin >> tempHours;hours.push_back(tempHours); // Add an element to hourscout << "Hourly pay rate for employee #";cout << (index + 1) << ": ";cin >> tempRate;payRate.push_back(tempRate); // Add an element to payRate

}cout << "Here is the gross pay for each employee:\n";cout.precision(2);cout.setf(ios::fixed | ios::showpoint);for (index = 0; index < numEmployees; index++){

float grossPay = hours[index] * payRate[index];cout << "Employee #" << (index + 1);cout << ": $" << grossPay << endl;

}}

Page 91: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

91

Program 7-24 (continued)Program Output with Example Input Shown in Bold

How many employees do you have? 3 [Enter] Enter the hours worked by 3 employees and their hourly rates.Hours worked by employee #1: 40 [Enter]Hourly pay rate for employee #1: 12.63 [Enter]Hours worked by employee #2: 25 [Enter]Hourly pay rate for employee #2: 10.35 [Enter]Hours worked by employee #3: 45 [Enter]Hourly pay rate for employee #3: 22.65 [Enter]Here is the gross pay for each employee:Employee #1: $505.20Employee #2: $258.75Employee #3: $1019.25

Page 92: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

92

Determining the Size of a vector

• Unlike arrays, vectors can report the number of elements they contain. This is accomplished with the size member function. Here is an example of a statement that uses the size member function:

numValues = set.size(); 

• In the statement above, assume that numValues is an int, and set is a vector. After the statement executes, numValues will contain the number of elements in the vector set.

Page 93: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

93

Determining the Size of a vector

• Example:

void showValues(vector<int> vect){

for (int count = 0; count < vect.size(); count++)cout << vect[count] << endl;

}

Page 94: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

94

Program 7-25// This program demonstrates the vector size // member function.#include <iostream.h>

#include <vector>using namespace std; // Function prototypevoid showValues(vector<int>); void main(void){

vector<int> values; 

for (int count = 0; count < 7; count++)values.push_back(count * 2);

showValues(values);} 

Page 95: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

95

Program 7-25 (continued)//**************************************************// Definition of function showValues. *// This function accepts an int vector as its *// argument. The value of each of the vector's *// elements is displayed. *//************************************************** void showValues(vector<int> vect){

for (int count = 0; count < vect.size(); count++)cout << vect[count] << endl;

Page 96: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

96

Program 7-25 (continued)

Program Output 024681012

Page 97: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

97

Removing Elements from a vector

• Use the pop_back member function to remove the last element from a vector.

collection.pop_back(); The statement above removes the last element from the collection vector.

Page 98: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

98

Program 7-26// This program demosntrates the vector size member function. #include <iostream.h>#include <vector>using namespace std; void main(void){

vector<int> values; 

// Store values in the vectorvalues.push_back(1);values.push_back(2);values.push_back(3);cout << "The size of values is " << values.size() << endl;

 // Remove a value from the vectorcout << "Popping a value from the vector...\n";values.pop_back();cout << "The size of values is now " << values.size() << endl;

 

Page 99: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

99

Program 7-26 (continued)// Now remove another value from the vectorcout << "Popping a value from the vector...\n";values.pop_back();cout << "The size of values is now " << values.size() << endl;

 // Remove the last value from the vectorcout << "Popping a value from the vector...\n";values.pop_back();cout << "The size of values is now " << values.size() << endl;

}

Program Output

The size of values is 3Popping a value from the vector...The size of values is now 2Popping a value from the vector...The size of values is now 1Popping a value from the vector...The size of values is now 0

Page 100: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

100

Clearing a vector

• To completely clear the contents of a vector, use the clear member function. Here is an example:

numbers.clear(); After the statement above executes, the numbers vector will be cleared of all its elements.

Page 101: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

101

Program 7-27// This program demosntrates the vector size member function.#include <iostream.h>#include <vector>using namespace std; void main(void){

vector<int> values(100); 

cout << "The values vector has “<< values.size() << " elements.\n";

cout << "I will call the clear member function...\n";values.clear();cout << "Now, the values vector has “

<< values.size() << " elements.\n";}

Page 102: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

102

Program 7-27 (continued)

Program Output The values vector has 100 elements.I will call the clear member function...Now, the values vector has 0 elements.

Page 103: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

103

Detecting an Empty vector

• To determine if a vector is empty, use the empty member function. The function returns true if the vector is empty, and false if the vector has elements stored in it. Here is an example of its use:

if (set.empty())cout << "No values in set.\

n"; 

Page 104: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

104

Program 7-28// This program demosntrates the vector's empty member function. #include <iostream.h>#include <vector>using namespace std; // Function prototypefloat avgVector(vector<int>); void main(void){

vector<int> values;int numValues;float average;

 cout << "How many values do you wish to average? ";cin >> numValues;

Page 105: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

105

Program 7-28 (continued)for (int count = 0; count < numValues; count++){

int tempValue; 

cout << "Enter a value: ";cin >> tempValue;values.push_back(tempValue);

}average = avgVector(values);cout << "Average: " << average << endl;

} //*************************************************************// Definition of function avgVector. *// This function accepts an int vector as its argument. If *// the vector contains values, the function returns the *// average of those values. Otherwise, an error message is *// displayed and the function returns 0.0. *//************************************************************* 

Page 106: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

106

Program 7-28 (continued)float avgVector(vector<int> vect){

int total = 0; // accumulatorfloat avg; // average

 if (vect.empty()) // Determine if the vector is empty{

cout << "No values to average.\n";avg = 0.0;

}else{

for (int count = 0; count < vect.size(); count++)total += vect[count];

avg = total / vect.size();}return avg;

Page 107: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

107

Program 7-28 (continued)Program Output with Example Input Shown in Bold

How many values do you wish to average?Enter a value: 12Enter a value: 18Enter a value: 3Enter a value: 7Enter a value: 9Average: 9 

Program Output with Example Input Shown in Bold

How many values do you wish to average? 0No values to average.Average: 0

Page 108: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

108

Summary of vector Member Functions

Member Function Description

at(element) Returns the value of the element located at element in the vector. Example:x = vect.at(5);The statement above assigns the value of the 5th element of vect to x.

capacity() Returns the maximum number of elements that may be stored in the vector without additional memory being allocated. (This is not the same value as returned by the size member function).Example:x = vect.capacity();The statement above assigns the capacity of vect to x.

Page 109: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

109

Summary of vector Member Functions

clear() Clears a vector of all its elements.Example:vect.clear();The statement above removes all the elements from vect.

empty() Returns true if the vector is empty. Otherwise, it returns false.Example:if (vect.empty()) cout << "The vector is empty.";The statement above displays the message if vect is empty.

pop_back() Removes the last element from the vector.Example:vect.pop_back();The statement above removes the last element of vect, thus reducing its size by 1.

Page 110: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

110

Summary of vector Member Functions

push_back(value) Stores a value in the last element of the vector. If the vector is full or empty, a new element is created.Example:vect.push_back(7);The statement above stores 7 in the last element of vect.

reverse() Reverses the order of the elements in the vector (the last element becomes the first element, and the first element becomes the last element.)Example:vect.reverse();The statement above reverses the order of the element in vect.

resize(elements, value)

Resizes a vector by elements elements. Each of the new elements is initialized with the value in value.Example:vect.resize(5, 1);The statement above increases the size of vect by 5 elements. The 5 new elements are initialized to the value 1.

Page 111: Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays

Starting Out with C++, 3rd Edition

111

Summary of vector Member Functions

swap(vector2) Swaps the contents of the vector with the contents of vector2.Example:vect1.swap(vect2);The statement above swaps the contents of vect1 and vect2.