270 likes | 468 Views
CIS162AB - C++. Arrays Juan Marquez 07_arrays1.ppt. Overview of Topics. For Loop Declaring Arrays Loading Arrays Arrays and Functions Partially Filled Arrays. Control Structures. 1 st Sequence Control 2 nd Selection Control (if, if-else) 3 rd Repetition Control (while, do-while)
E N D
CIS162AB - C++ Arrays Juan Marquez 07_arrays1.ppt
Overview of Topics • For Loop • Declaring Arrays • Loading Arrays • Arrays and Functions • Partially Filled Arrays
Control Structures • 1st Sequence Control • 2nd Selection Control (if, if-else) • 3rd Repetition Control (while, do-while) • 4th Case Control (switch ) • The for loop is a repetition control structure as are the while and do-while loops.
count = 3; while (count > 0) { cout << count; count--; } Output: 3 2 1 count = 3; do { cout << count; count--; }while (count > 0); Output: 3 2 1 While & Do-While Reviewed
For-loop • Good when counting with fixed increments. • Compares to a while loop. • Controlling variable must be initialized. • Boolean expression must be true to enter the loop, so it is possible that the loop will not be executed. • Controlling variable is usually altered as part of the for statement in the update action. • For loops can also be nested.
While Loop int loopCnt = 1; //Initialization while (loopCnt <= empCnt) //Boolean expression { getRate() getHours() calcGross() displayDetails() loopCnt++; //Update action }
For-loop //for (Initialization action; Boolean expression; Update action) int loopCnt; for (loopCnt = 1; loopCnt <= empCnt; loopCnt++) { //Do NOT place a semicolon after the closing parentheses. getRate() getHours() calcGross() displayDetails() }
For Loops and Arrays • For loops are used extensively with Arrays. • Before we get into declaring, loading and processing arrays, let’s look at what an array is.
Array is a different word for a table. A table is made up of columns and rows. Just like an Excel spreadsheet. Columns are labeled with letters and rows are labeled with numbers. Arrays are Tables
Array Defined • An array is used to process a collection of data all of which is of the same data type (int, double, char, etc). • First we’ll look at single dimensional arrays (one column, many rows). • Think of a single dimensional array as a list of variables.
Array Example int qty1, qty2, qty3; //3 integer variables int qty[3]; //3 integer variablesbase type arrayName[ arraySize ]; • An array of 3 elements of type int is created. • The arraySize specifies the number elements that can be stored and is used to determine how much memory to allocate. • After the array is created, its size cannot be changed.
Memory Management • C++ needs two pieces of information for memory management. • The memory address of the first entry. • The base type, which tells it how many bytes each element is: int = 4 bytes, double = 8 bytes, etc. • After creating the array, the size is not stored anywhere.
ArraySize as a Variable • Since the size of the array is not stored by C++, it is best to store the arraySize in a variable.const int MAX_SIZE = 3;int qty[MAX_SIZE]; • This would make the program easier to maintain, and the variable can used to control the loading and processing of the array instead of hardcoding a constant (like 3) throughout the program.
Array Index • Arrays are allocated consecutive memory. • Each element is referenced using an index. • Index are integers. • The number of elements that can be indexed is the declared size (arraySize). • The first element in the array is referenced with an index of zero. • The last index should be the arraySize – 1. • The valid index values for int qty[3], are 0, 1, and 2.
Memory Map 1st element is index 0, last element is arraySize – 1;
Index Out Of Range • The programmer must make sure that the logic in the program does not allow the index to exceed the arraySize – 1. • This is call being out of range. • C++ does not check if the index is out of range. • If the the index value goes out of range, the program would be altering other values in memory. • Negative values are also out of range.
Array Processing • Declare Array • Load Array • After creating the array, data must be loaded. • Use constant variables with the arraySize to prevent out of range errors. • Process Array • Use individual elements in calculations or function calls. • Send entire arrays to functions for processing. • Sort, Search, Display • Use a lot of for-loops.
Load Array cout << “Enter three quantities separated by a space: “ ; for (int index = 0; index < MAX_SIZE; index++) { cin >> qty[index]; } //OK to use short names for index ( i, j, k, x, y, z, etc.) for (int i = 0; i < MAX_SIZE; i++) { cin >> qty[ i ]; }
Process Arrays – Individual Elements //int qty[MAX_SIZE]; for (int i = 0; i < MAX_SIZE; i++) {displayQty(qty[i]); //argument is one int value } void displayQty(int qty) //parameter takes one int value {cout << qty; }
Process Arrays – Entire Array void displayQty(int qty[ ], int arraySize); //array parameter void main( ) { const int MAX_SIZE = 3; int qty[MAX_SIZE]; displayQty(qty, MAX_SIZE); //array name as argument } void displayQty(int qty[ ], int arraySize) //array parameter, requires size {for (int i = 0; i < arraySize; i++){ cout << qty[i] ;} }
Arrays as Parameters • Use array parameters. • Array parameters are like call-by-reference parameters, because the memory address is sent. • Changes made in functions are reflected in main() or calling function. • Size of array is important for processing, so it must be passed to the function.
Array Parameter • Address of first entry [0] is passed. • The base type tells how big each element is (int, double, etc). • Array size is passed as a separate argument, because it is not included in array parameter. • This is good, because the array size can vary, and the same function would work.
const Array Parameter • To prohibit functions from changing values in arrays, use the const modifier on the prototype and definition. • displayQty(const int qty[ ], int arraySize); • This will emulate a call-by-value.
Occurs when the array size is larger than needed. Array size is set for maximum entries, but array may not always be filled. Use MAX_SIZE to control loading. Count the entries as loaded. Then use the final count as the “array size” for processing (ie: numberUsed, numbersEntered). Partially Filled Arrays
Loading Partially Filled Arrays const int MAX_SIZE = 20; int testScore[MAX_SIZE], numbersEntered, i ; cout << “Enter up to 20 test scores, or a negative value to end input: “; for (i = 0; i < MAX_SIZE; i++) {cin >> testScore[i]; //value 50, 40, 100, 30, 10, 20, -1if ( testScore[i] < 0 ) //index 0 1 2 3 4 5 6{ break;} } numbersEntered = i;
Using numbersEntered • The testScore array can hold up to 20 scores. • We entered 6 scores and a –1 to end input. • Only 6 scores should be processed, not the –1. //numbersEntered is 6, so index will be 0 – 5. void displayTestScores(int testScore[ ], int numbersEntered) { for (int i = 0; i < numbersEntered; i++) { cout << testScore[i]; } }
Summary • For Loops • Creating Arrays • Loading Arrays • Processing Arrays • Partially Filled Arrays