Chapter 7 Arrays Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting Out with C++, Tony Gaddis, 2nd Ed. C++ Programming, Namiq Sultan 1 7.1 Arrays Hold Multiple values • Unlike regular variables, arrays can hold multiple values. C++ Programming, Namiq Sultan 2 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 C++ Programming, Namiq Sultan 3 Figure 7-2 int Days[6]; C++ Programming, Namiq Sultan 4 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 double dDistance[1000]; 1000 8 bytes 8000 bytes C++ Programming, Namiq Sultan 5 7.2 Accessing Array elements • The individual elements of an array are assigned unique subscripts. These subscripts are used to access the elements. C++ Programming, Namiq Sultan 6 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> int 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]; C++ Programming, Namiq Sultan 7 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; } C++ Programming, Namiq Sultan 8 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 C++ Programming, Namiq Sultan 9 Figure 7-7 C++ Programming, Namiq Sultan 10 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> int 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; } C++ Programming, Namiq Sultan 11 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 C++ Programming, Namiq Sultan 12 7.4 Array Initialization • Arrays may be initialized when they are declared. C++ Programming, Namiq Sultan 13 Program 7-6 // This program displays the number of days in each month. // It uses a 12-element int array. #include <iostream> 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"; } } C++ Programming, Namiq Sultan 14 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. C++ Programming, Namiq Sultan 15 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> 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; } } C++ Programming, Namiq Sultan 16 Program Output Character --------A B C D E F G H I J ASCII Code ---------65 66 67 68 69 70 71 72 73 74 C++ Programming, Namiq Sultan 17 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}; C++ Programming, Namiq Sultan 18 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}; C++ Programming, Namiq Sultan 19 Initializing With Strings • When initializing a character array with a string, simply enclose the string in quotation marks: char name[] = “Warren”; C++ Programming, Namiq Sultan 20 Figure 7-11 C++ Programming, Namiq Sultan 21 Program 7-9 // This program displays the contents of two char arrays. #include <iostream> int main() { char name1[] = "Holly"; char name2[] = {'W', 'a', 'r', 'r', 'e', 'n', '\0'}; cout << name1 << endl; cout << name2 << endl; } C++ Programming, Namiq Sultan 22 Program Output Holly Warren C++ Programming, Namiq Sultan 23 7.5 Processing Array Contents • Individual array elements are processed like any other type of variable. C++ Programming, Namiq Sultan 24 Program 7-10 // This program stores, in an array, the hours worked by 5 // employees who all make the same hourly wage. #include <iostream> 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]; } C++ Programming, Namiq Sultan 25 cout << "Enter the hourly pay rate for the employees: "; cin >> payRate; cout << "Here is the gross pay for each employee:\n"; for (index = 0; index < 5; index++) { float grossPay = hours[index] * payRate; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; } } C++ Programming, Namiq Sultan 26 Program Output with Example Input 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.75 Employee #2: $127.50 Employee #3: $191.25 Employee #4: $255.00 Employee #5: $510.00 C++ Programming, Namiq Sultan 27 7.8 Arrays As Function Arguments • To pass an array as an argument to a function, pass the name of the array. C++ Programming, Namiq Sultan 28 Program 7-13 // This program demonstrates that an array element is // passed to a function like any other variable. #include <iostream> using namespace std; void ShowValue(int Num) { cout << Num << " "; } int main() { int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40}; for (int Cycle = 0; Cycle < 8; Cycle++) ShowValue(collection[Cycle]); } C++ Programming, Namiq Sultan 29 Program Output 5 10 15 20 25 30 35 40 C++ Programming, Namiq Sultan 30 Program 7-14 // This program demonstrates an array being passed to a function. #include <iostream> // Definition of function showValues. This function accepts an array void showValues(int nums[]) { for (int index = 0; index < 8; index++) cout << nums[index] << " "; } int main() { int collection[8] = {5, 10, 15, 20, 25, 30, 35, 40}; showValues(collection); // Passing address of array collection } C++ Programming, Namiq Sultan 31 Program Output 5 10 15 20 25 30 35 40 C++ Programming, Namiq Sultan 32 Program 7-16 // This program uses a function that display the contents // of an integer array of any size. #include <iostream> void showValues(int nums[], int elements){ for (int index = 0; index < elements; index++) cout << nums[index] << " "; } 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); C++ Programming, Namiq Sultan } 33 Program Output 5 10 15 20 25 30 35 40 2468 1 2 3 4 5 6 7 8 9 10 11 12 C++ Programming, Namiq Sultan 34 Program 7-17 // This program uses a function that doubles the contents // of the elements within an array. #include <iostream> void doubleArray(int [], int); const int arraySize = 12; // Function prototype 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"; C++ Programming, Namiq Sultan 35 for (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; } C++ Programming, Namiq Sultan 36 Program Output The array values are: 1 2 3 4 5 6 7 8 9 10 11 12 After calling doubleArray, the values are: 2 4 6 8 10 12 14 16 18 20 22 24 C++ Programming, Namiq Sultan 37 Examples • C++ program to find the largest number in a given array. • Repeat (1) using a function that accepts an array and returns the largest element. • C++ program to find the largest two number s in a given array. • Construct an array of Fibonacci series. • Sort an array of three elements. HW: • Reverse the elements of a given array. • Count the repetition of number 0 in a given array. • Find the sum of smallest and largest elements of a given array. C++ Programming, Namiq Sultan 38 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. C++ Programming, Namiq Sultan 39 Program 7-18 // This program demonstrates a two-dimensional array. #include <iostream> int main() { float sales[3][4]; // 2D array, 3 rows and 4 columns. float totalSales = 0; // To hold the total sales. int dir, qtr; // Loop counters. cout << "This program calculate the total sales of\n"; cout << "all the company's divisions.\n"; cout << "Enter the following sales information:\n\n"; C++ Programming, Namiq Sultan 40 // 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. } C++ Programming, Namiq Sultan 41 // Nested loops to add all the elements. for (div = 0; div < 3; div++) for (qtr = 0; qtr < 4; qtr++) totalSales += sales[div][qtr]; cout << "The total sales for the company are: $"; cout << totalSales << endl; } C++ Programming, Namiq Sultan 42 Program Output with Example Input This program will calculate the total sales of all 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] C++ Programming, Namiq Sultan 43 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 C++ Programming, Namiq Sultan 44 Two-dimensional Array Initialization • Both of the following declarations perform the same initialization: int Hours[3][2]={{8,5},{7,9},{6,3}}; int Hours[3][2]={8,5,7,9,6,3}; • It is helpful to write the declaration as: int Hours[3][2]={ 8,5, 7,9, 6,3}; C++ Programming, Namiq Sultan 45 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. C++ Programming, Namiq Sultan 46 Program 7-19 // This program demonstrates a function that accepts a two-dimensional // array as an argument. #include <iostream> void showArray(int [][4], int); // Function prototype int main() { int Table[3][4] ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; C++ Programming, Namiq Sultan 47 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); } C++ Programming, Namiq Sultan 48 // 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<< Array[x][y] << “\t“; cout << endl; } } C++ Programming, Namiq Sultan 49 7.10 Arrays of Strings • A two-dimensional array of characters can be used as an array of C-strings. C++ Programming, Namiq Sultan 50 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> 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"; } } C++ Programming, Namiq Sultan 51 Program Output 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. C++ Programming, Namiq Sultan 52 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]; C++ Programming, Namiq Sultan 53 Homework • • • • • Add two 3x3 matrices and put the result in a third matrix. Exchange the elements of first column and second column of a given matrix. Find the sum of elements of upper-right triangle of a matrix. Print the lower-left triangle of a matrix. Write a program to print transpose of a matrix . C++ Programming, Namiq Sultan 54