Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS102 Introduction to Computer Programming Chapter 7 Arrays.

Similar presentations


Presentation on theme: "CS102 Introduction to Computer Programming Chapter 7 Arrays."— Presentation transcript:

1 CS102 Introduction to Computer Programming Chapter 7 Arrays

2 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

3 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 Size Declarator

4 Memory Requirements of Arrays ArrayNumber Element Size of the DeclarationElements Size Array char letters[25];251 byte25 bytes int Rings[100];1002 bytes200 bytes long Miles[84];844 bytes336 bytes float Temp[12];124 bytes48 bytes double big[1000];10008 bytes8000 bytes Concept - The amount of memory used by an array = number of elements * size of each element in bytes

5 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 621354 510243 Num Note: 1st element always starts at 0 Size declarator Subscript

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

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

8 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 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. Array size 0 to Array Size-1 first subscript

9 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 are Employee 1: 20 Employee 2: 12 Employee 3: 40 Employee 4: 30 Employee 5: 30 Employee 6: 15 Notice that the array subscript and the display are different

10 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

11 Program 7-4 (Modified) /* This program accesses an unused area of memory by reading values beyond an array's boundary.*/ #include using namespace std; int main() { short OverFlow[3];//Might be after the following array in memory short 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; }

12 Checkpoint 7.1-7.3 7.1 Declare the following arrays A.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 doubles 7.4 What is the difference between an array's size declarator and a subscript Negative Size Declarator Not an integer Must be an integer constant O,1,2,3 The size declarator is used to define the size of the array A subscript is used to select an individual element of an array

13 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 declared

14 Program 7-5 #include using namespace std; int main() { int Days[12]; Days[0] = 31; // January Days[1] = 28; // February Days[2] = 31; // March Days[3] = 30; // April Days[4] = 31; // May Days[5] = 30; // June Days[6] = 31; // July Days[7] = 31; // August Days[8] = 30; // September Days[9] = 31; // October Days[10] = 30; // November Days[11] = 31; // December 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 displays the number of days in each month by assigning values to a 12- element int array.

15 Program 7-6 // This program displays the number of days in each month. It uses a 12-element int array.*/ #include 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

16 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 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 CharacterASCII Code --------- ---------- A65 B66 C67 D68 E69 F70 G71 H72 I73 J74 This program uses character literals to initialize a char array

17 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 021300 510243 Num

18 Program 7-8 //This program has a partially initialized array. #include 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: 1 2 4 8 000000

19 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 21354 10243 Num Note: if you have a partial initialization list the array will be sized too small

20 Initializing With Strings You can let C++ size the array for you –it will automatically add an element for the \0 char Name[] = "Frank"; If you provide the size declarator C++ will fill up the unused elements with \0 char Name[6] = "Ann"; Concept - Arrays are initialized with strings differently than with other types of values. rFakn 10243 nAn\0 10243 5 5

21 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.cpp D:\Documents and Settings\dledward\My Documents\c++\bc45\bin\Cpp1.cpp(3) : error C2117: 'Harry' : array bounds overflow Error executing cl.exe. Cpp1.obj - 1 error(s), 0 warning(s)

22 Program 7-9 /* This program displays the contents of two char arrays.*/ #include 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 Holly Warren 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

23 Processing Array Contents An Array element can be used anywhere a variable can be used Num[1] = Num[2] * Num[3];12 Num[1] = ++Num[2];4 Num[1] = Num[2] ++;4 Num[1] = Num[++ Num[2]];7 Num[1] = Num[Num[2]++];7 Concept - Individual array elements are processed like any other type of variable. ?1354 10243 Num 6 5 78 67

24 Program 7-10 /* This program stores, in an array, the hours worked by 5 employees who all make the same hourly wage.*/ #include 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.75 Employee #2: $127.50 Employee #3: $191.25 Employee #4: $255.00 Employee #5: $510.00

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

26 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. 1510253540 10243 Hours 102101103105104 7.25.56.07.25.5 Salary Emp_Num

27 Program 7-12 /* This program stores, in two arrays, the hours worked by 5 employees, and their hourly pay rates.*/ #include 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

28 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. This will try to assign the address of array Num to Location int 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];

29 Arrays as Function Arguments #include 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. Function Prototype Function Call (call by reference) Function Definition Pointer to array

30 Program 7-13 /* This program demonstrates that an array element is passed to a function like any other variable. */ #include using namespace std; // Function prototype void 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

31 Program 7-14 // This program demonstrates an array being passed to a function. #include 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

32 Program 7-15 // This program demonstrates an array being passed to a function. #include using namespace std; void ShowValues(int []);// Function prototype int 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 40 2 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

33 Program 7-16 /* This program uses a function that can display the contents of an integer array of any size.*/ #include 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 40 2 4 6 8 1 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

34 Program 7-17 /* This program uses a function that doubles the contents of the elements within an array.*/ #include using namespace std; void DoubleArray(int [], int);// Function prototype const 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 12 After 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

35 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. Rowcolumn 2,12,02,22,42,3 10243 2 0,10,00,20,40,3 1,11,01,21,41,3 1 0 Row column

36 Program 7-18 // This program demonstrates a two- dimensional array. #include using namespace std; #include 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

37 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. 2.5101103105.4.5 10 Row 000111 column

38 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 row Array address + (Row number x Column size x Sizeof (Data Type))

39 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. rFakn\0 nAn iBl l aMr y column Row 2 3 1 0 123405 Address of row 3

40 Program 7-19 /* This program demonstrates a function that accepts a two-dimensional array as an argument.*/ #include using namespace std; #include void ShowArray(int [][4], int); // Function prototype int 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

41 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 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


Download ppt "CS102 Introduction to Computer Programming Chapter 7 Arrays."

Similar presentations


Ads by Google