cs102 introduction to computer programming chapter 7 arrays

41
CS102 Introduction to Computer Programming Chapter 7 Arrays

Upload: edgar-montgomery

Post on 27-Dec-2015

241 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CS102 Introduction to Computer Programming Chapter 7 Arrays

CS102Introduction to Computer

ProgrammingChapter 7 Arrays

Page 2: CS102 Introduction to Computer Programming Chapter 7 Arrays

Chapter 7 Topics• Arrays hold multiple values

– Memory requirements of arrays

• Accessing array elements– Inputting and outputting array contents

• No bounds checking in C++• Array initialization

– Partial array sizing– Implicit array sizing – Initializing with strings

• Auditorium Seating

Page 3: CS102 Introduction to Computer Programming Chapter 7 Arrays

Arrays Hold Multiple Values

• An array is declared just like a regular variable plus a size declarator.

Data_type Variable_name [size];

float array_of_numbers [10];• Size Declarator must be a constant integer

expression

Concept - Unlike regular variables Arrays can hold multiple values

Concept - Unlike regular variables Arrays can hold multiple values

Size Declarator

Page 4: CS102 Introduction to Computer Programming Chapter 7 Arrays

Memory Requirements of Arrays

Array Number Element Size of theDeclaration Elements Size Array

char letters[25]; 25 1 byte 25 bytes

int Rings[100]; 100 2 bytes 200 bytes

long Miles[84]; 84 4 bytes 336 bytes

float Temp[12]; 12 4 bytes 48 bytes

double big[1000]; 1000 8 bytes 8000 bytes

Concept - The amount of memory used by an array = number of elements * size of each element in bytes

Concept - The amount of memory used by an array = number of elements * size of each element in bytes

Page 5: CS102 Introduction to Computer Programming Chapter 7 Arrays

• Subscript numbering in C++ always starts with zero.

int Num[6];

Num[2] = = 3

• Unless the array is declared as a global array, the uninitialized elements contain garbage

Accessing Array Elements

Concept - The individual elements of an array are assigned unique subscripts

Concept - The individual elements of an array are assigned unique subscripts

621 3 54

510 2 43

NumNote: 1st element always starts at 0

Size declarator

Subscript

Page 6: CS102 Introduction to Computer Programming Chapter 7 Arrays

Inputting and Outputting Array Contents

• Subscripts may be variables– any integer expression is acceptable

• A for loop can be used to index through the contents of an array

• int num[6];

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

cout << num[count];

Concept - Array elements may be used with the cin and cout objects just like any other variable.

Concept - Array elements may be used with the cin and cout objects just like any other variable.

Page 7: CS102 Introduction to Computer Programming Chapter 7 Arrays

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>using namespace std;int main(){

short Hours[6];cout << "Enter the hours worked by six

employees: ";cin >> Hours[0];cin >> Hours[1];cin >> Hours[2];cin >> Hours[3];cin >> 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;

}

Program Output 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

The individual elements of an array can be used just like any other variable

Page 8: CS102 Introduction to Computer Programming Chapter 7 Arrays

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>using namespace std;int main(){

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;return 0;

}

Program Output 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

A for loop is a good tool for indexing through the contents of an array.

Arraysize

0 to ArraySize-1

firstsubscript

Page 9: CS102 Introduction to Computer Programming Chapter 7 Arrays

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.int main(){

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";for (Count = 1; Count <= 6; Count++){ cout << "Employee " << Count << ": "; cout << Hours[Count - 1] << endl;}return 0;

}

Program Output

The current index value can be used to communicate with the user

Enter 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

Notice that the array subscript and the display are different

Page 10: CS102 Introduction to Computer Programming Chapter 7 Arrays

No bounds Checking in C++

• You can access any place in the computers memory from a C++ array;– Negative subscripts are before the beginning of

the array– If you write values outside the boundaries of an

array you will overwrite adjacent data

Concept - C++ gives you the freedom to store data past an array's boundaries

Concept - C++ gives you the freedom to store data past an array's boundaries

Page 11: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-4 (Modified)/* This program accesses an unused area of memory

by reading values beyond an array's boundary.*/#include<iostream>using namespace std;int main(){

short OverFlow[3];//Might be after the following array in memoryshort Values[3]; // An array of 3 short integers.cout << "Display the contents of OverFlow\n";for (int Count = 0; Count < 3; Count++)

cout << OverFlow[Count] << endl;cout << "I will store 6 numbers in a 3 element array!\n";

for (int Count = 0; Count < 6; Count++)Values[Count] = 100 + Count;

cout << "If you see this message, it means the computer\n";

cout << "has not crashed! Here are the numbers:\n";

cout << "I will read 6 numbers from a 3 element array!\n";

for ( Count = 0; Count < 6; Count++)cout << Values[Count] << endl;

cout <<endl;for ( Count = 0; Count < 3; Count++)

cout << OverFlow[Count] << endl;return 0;}

Page 12: CS102 Introduction to Computer Programming Chapter 7 Arrays

Checkpoint 7.1-7.37.1 Declare the following arraysA.empNums, a 100-element arrays of ints

B.payRate, a 25-element array of floats

C.miles, a 14 element array of longs

D.cityNane, a 26-element array of chars

E.lightYears, a 1000-element array of doubles

int empNums [100];

float payRate [25];

long miles [14];

char cityNane [26];

double lightYears [1000];

7.2 What's wrong with the following array declarations?

int readings[-1]; float neasurements [4.5];Int size; char name[size];

7.3 What would the valid subscript values be in a four-element array of doubles7.4 What is the difference between an array's size declarator and a subscript

Negative Size Declarator

Not an integerMust be an integer constant

O,1,2,3

The size declarator is used to define the size of the arrayA subscript is used to select an individual element of an array

Page 13: CS102 Introduction to Computer Programming Chapter 7 Arrays

Array Initialization

• Use an initialization list when the array is defined– Values are enclosed in braces and separated by commas

– May be on multiple lines.

– Can not have more values that the array has elements

int Num[6] = {1,2,

3,4,

5,6};

Concept - Arrays may be initialized when they are declaredConcept - Arrays may be initialized when they are declared

Page 14: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-5#include<iostream>using namespace std;int main(){

int Days[12];Days[0] = 31; // JanuaryDays[1] = 28; // FebruaryDays[2] = 31; // MarchDays[3] = 30; // AprilDays[4] = 31; // MayDays[5] = 30; // JuneDays[6] = 31; // JulyDays[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";

}return 0:

}

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.

This program displays the number of days in each month by assigning values to a 12-element int array.

Page 15: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-6// This program displays the number of days in

each month. It uses a 12-element int array.*/#include<iostream>using namespace std;int main(){

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";}return 0;

}

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

This program uses an initialization list to put values in an array

Page 16: CS102 Introduction to Computer Programming Chapter 7 Arrays

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>using namespace std;int main(){

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;

}return 0;

}

Program Output Character ASCII Code--------- ----------

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

This program uses character literals to initialize a char array

Page 17: CS102 Introduction to Computer Programming Chapter 7 Arrays

Partial Array Sizing• If you leave an element uninitialized every

element after must be left uninitialized

• Uninitialized elements are set to zero– If none of the elements are initialized they will

all contain garbage.

int Num[6] = {1,2,3};

Concept - C++ allows you to partially initialize an array Concept - C++ allows you to partially initialize an array

021 3 00

510 2 43

Num

Page 18: CS102 Introduction to Computer Programming Chapter 7 Arrays

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

array.#include<iostream>using namespace std;int main(){

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;return 0;

}

Program Output

Here are the contents of the array:

1248000

Page 19: CS102 Introduction to Computer Programming Chapter 7 Arrays

Implicit Array Sizing

• If the size declarator is left empty C++ will count the elements in the initialization list and automatically size the array

int num[ ] = {1,2,3,4,5};

Concept - C++ can determine how large the array should be Concept - C++ can determine how large the array should be

21 3 54

10 2 43

Num

Note: if you have a partial initialization list the array will be sized too small

Page 20: CS102 Introduction to Computer Programming Chapter 7 Arrays

Initializing With Strings• You can let C++ size the array for you

– it will automatically add an element for the \0char Name[] = "Frank";

• If you provide the size declarator C++ will fill up the unused elements with \0char Name[6] = "Ann";

Concept - Arrays are initialized with strings differently than with other types of values.

Concept - Arrays are initialized with strings differently than with other types of values.

rF a kn

10 2 43

nA n \0\0

10 2 43

\0

\0

5

5

Page 21: CS102 Introduction to Computer Programming Chapter 7 Arrays

Sizing arrays continued• If you specify a size declarator that is smaller than the

initialization list the compiler will provide an error message

int main (){

char name [5] = "Harry";return 0;

}--------------------Configuration: Cpp1 - Win32 Debug--------------------Compiling...Cpp1.cppD:\Documents and Settings\dledward\My Documents\c++\bc45\bin\Cpp1.cpp(3) : error C2117: 'Harry' : array bounds overflowError executing cl.exe.Cpp1.obj - 1 error(s), 0 warning(s)

Page 22: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-9/* This program displays the contents

of two char arrays.*/#include<iostream>using namespace std;

int main(){

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

cout << Name1 << endl;cout << Name2 << endl;return 0;

}Program Output HollyWarren

In this example a sting constant and a string of character literal are used to initialize an array.

Note: The NULL character is not automatically provided for a list of character literals

Page 23: CS102 Introduction to Computer Programming Chapter 7 Arrays

Processing Array Contents• An Array element can be used anywhere a variable

can be used

Num[1] = Num[2] * Num[3]; 12Num[1] = ++Num[2]; 4Num[1] = Num[2] ++; 4Num[1] = Num[++ Num[2]]; 7Num[1] = Num[Num[2]++]; 7

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

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

?1 3 5410 2 43

Num 65

7 86 7

Page 24: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-10/* This program stores, in an array, the hours worked by

5 employees who all make the same hourly wage.*/#include<iostream>using namespace std;int main(){

int Hours[5];float PayRate, GrossPay;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];}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++){

GrossPay = Hours[Index] * PayRate;cout << "Employee #" << (Index + 1);cout << ": $" << GrossPay << endl;}return 0;

}Program Output Enter the hours worked by 5 employees who all earn 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 25: CS102 Introduction to Computer Programming Chapter 7 Arrays

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>using namespace std;int main(){

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

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, 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;}else GrossPay = Hours[Index] * PayRate; cout << "Employee #" << (Index + 1) cout << ": $" << GrossPay << endl;}return 0;

}

Page 26: CS102 Introduction to Computer Programming Chapter 7 Arrays

Using Parallel Arrays

• If data of different types are related to each other– they can be stored in arrays of equal length– a common subscript can be used to index into

the different arrays and locate the related data

Concept - By using the same subscript, you can build relationships between data stored in two or more arrays.

Concept - By using the same subscript, you can build relationships between data stored in two or more arrays.

1510 25 3540

10 2 43

Hours

102101 103 105104

7.25.5 6.0 7.25.5SalaryEmp_Num

Page 27: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-12/* This program stores, in two arrays, the hours

worked by 5 employees, and their hourly pay rates.*/

#include<iostream>using namespace std;int main(){

int Hours[5];float PayRate[5];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];

}

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

}

With parallel arrays the same index value can be used to access adjacent data

Page 28: CS102 Introduction to Computer Programming Chapter 7 Arrays

Thou Shall Not Assign• If only the name of an array is used without a subscript

the computer will evaluate it as the address of the array

Concept - You can not use the assign operator to copy one array's contents to another using one statement.

Concept - You can not use the assign operator to copy one array's contents to another using one statement.

This will try to assign the address of array Num to Locationint Location[5], Num[5]; Location = Num;Note: This actually will generate a compiler error

This will assign the values of Num to Location

int Location[5], Num[5];

for (I = 0; I < 5; I++)

Location[I] = Num[I];

Page 29: CS102 Introduction to Computer Programming Chapter 7 Arrays

Arrays as Function Arguments#include<iostream>using namespace std;

void ShowValues(int []);

int main()

{

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

ShowValues(Collection);

}

void ShowValues(int Nums[])

{

for (int Index = 0; Index < 8; Index++)

cout << Nums[Index] << " ";

}

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

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

Function Prototype

Function Call (call by reference)

Function Definition

Pointer to array

Page 30: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-13/* This program demonstrates that an array element

is passed to a function like any other variable. */#include<iostream>using namespace std;// Function prototypevoid ShowValue(int);

int main(){

int Collection[8] = {5, 10, 15, 20, 25, 30, 35, 40};for (int Cycle = 0; Cycle < 8; Cycle++)ShowValue(Collection[Cycle]);return 0;

}

void ShowValue(int Num){

cout << Num << " ";}

Program Output 5 10 15 20 25 30 35 40

A single element of an array can be sent like any other variable

Page 31: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-14// This program demonstrates an array being

passed to a function.#include<iostream>using namespace std;void ShowValues(int []); // Function prototype

int main(){

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

ShowValues(Collection);return 0; }

void ShowValues(int Nums[]){

for (int Index = 0; Index < 8; Index++)cout << Nums[Index] << " ";

}

Program Output 5 10 15 20 25 30 35

40

Note: the size declarator is not needed in the prototype or function header

the [] are not needed at all in the function call

The function must know how large the array is

An entire array can also be sent to a function

Page 32: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-15// This program demonstrates an array being

passed to a function.#include<iostream>using namespace std;void ShowValues(int []); // Function prototypeint main(){

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

return 0;}void ShowValues(int Nums[]){

for (int Index = 0; Index < 8; Index++)cout << Nums[Index] << " ";

}

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

This works fine if the arrays are the same size

One function can be used to process different arrays

Page 33: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-16/* This program uses a function that can

display the contents of an integer array of any size.*/

#include<iostream>using namespace std;void ShowValues(int [], int); // Function

prototype

int main(){

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);return 0;}

void ShowValues(int Nums[], int Elements)

{for (int Index = 0; Index < Elements; Index++)

cout << Nums[Index] << " ";}

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

If the arrays are of different size then more information is needed

A function can handle arrays of various sizes

Page 34: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-17/* This program uses a function that doubles the

contents of the elements within an array.*/#include<iostream>using namespace std;void DoubleArray(int [], int); // Function

prototypeconst int ArraySize = 12;

int main(){

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

for (int Index = 0; Index < ArraySize; Index++)

cout << Set[Index] << " ";cout << endl;return 0;

}void DoubleArray(int Nums[], int

Size){

for (int Index = 0; Index < Size; Index++)

Nums[Index] *= 2;}

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

Note: the original values have been modified by the function

An array is always passed by reference

Page 35: CS102 Introduction to Computer Programming Chapter 7 Arrays

Two Dimensional Arrays

• Thinks of two dimensional arrays as having rows and columns

data_type array_name [x][y];

Concept - A two dimensional array is like several identical arrays put together.

Concept - A two dimensional array is like several identical arrays put together.

Row column

2,12,0 2,2 2,42,3

10 2 43

2

0,10,0 0,2 0,40,3

1,11,0 1,2 1,41,310Row

column

Page 36: CS102 Introduction to Computer Programming Chapter 7 Arrays

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

#include<iostream>using namespace std;#include <iomanip>using namespace std;int main(){// 2D array, 3 rows and 4 columns.

float Sales[3][4];// Running total to hold the total sales.

float TotalSales = 0; // Loop counters.

int Row, Col;cout << "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 (Row = 0; Row < 3; Row++)

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

{cout << "Division " << (Row + 1);cout << ", Quarter " << (Col + 1)

<< ": $";cin >> Sales[Row][Col];

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

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

for (Col = 0; Col < 4; Col++) TotalSales += Sales[Row][Col];

cout << precision(2) << fixed << showpoint;cout << "The total sales for the company are: $";cout << TotalSales << endl;}Note: The running total could have been included in the first set of nested loops

Executes 12 times

Executes 3 times

Page 37: CS102 Introduction to Computer Programming Chapter 7 Arrays

Passing two dimensional arrays to functions

• It is necessary to provide the number of columns because of the way a two dimensional array is stored in memory

• The compiler must know how many bytes to store for each row

Concept - A two dimensional array may be passed as an argument to a function, but the the column size must be

specified in the parameter list.

Concept - A two dimensional array may be passed as an argument to a function, but the the column size must be

specified in the parameter list.

2.5101 103 105.4 .5

10Row

00 0 111column

Page 38: CS102 Introduction to Computer Programming Chapter 7 Arrays

Passing a two dimensional array• Arrays organize data in contiguous memory locations.

– For single dimensional arrays there is only one element in each row

• If there are multiple values in a row, the compiler has to know where the row ends – Two dimensional arrays have more than one value in a row

• The Column length will determine this– The column length times the size of the data type will gives the address

of the next rowArray address + (Row number x Column size x Sizeof (Data Type))

Page 39: CS102 Introduction to Computer Programming Chapter 7 Arrays

char names[4][6];

cout <<names[3]; Mary

Arrays of Strings

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

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

rF a kn \0

nA n \0\0 \0

iB l \0l \0

aM r \0y \0

column

Row

2

3

1

01 2 3 40 5

Address of row 3

Page 40: CS102 Introduction to Computer Programming Chapter 7 Arrays

Program 7-19/* This program demonstrates a function

that accepts a two-dimensional array as an argument.*/

#include<iostream>using namespace std;#include <iomanip.h>void ShowArray(int [][4], int); // Function

prototypeint main(){

int Table1[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};int Table2[4][4] = {{10, 20, 30, 40}, {50, 60, 70, 80}, {90, 100, 110, 120}, {130, 140, 150, 160}};

cout << "The contents of Table1 are:\n";ShowArray(Table1, 3);cout << "The contents of Table2 are:\n";ShowArray(Table2, 4);

return 0;}

// Function Definition for ShowArray./* This function accepts a two-dimensional integer array as an argument. The array must have four columns. The second argument, Rows, specifies the number of rows in the array. The function displays the contents of the array.*/void ShowArray(int Array[][4], int Rows){ for (int X = 0; X < Rows; X++)

{ for (int Y = 0; Y < 4; Y++)

{ cout << setw(4) << Array[X][Y] << " ";

}cout << endl;

}}

Program Output The contents of Table1 are: 1 2 3 4 5 6 7 8 9 10 11 12

The contents of Table2 are: 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160

Page 41: CS102 Introduction to Computer Programming Chapter 7 Arrays

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>using namespace std;int main(){

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";}return 0;

}

January 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.

Program Output