1 / 53

Chapter 12

Chapter 12. Array. Convert Numbers in Different Base Systems. Generate values to a series of numbers in different base systems: Base is between 2 and 9; Maximum number of digits is 100. Number is NOT in reverse order! Example: 3 1201 Value = 1*3 3 + 2*3 2 + 0*3 + 1 = 46

arista
Télécharger la présentation

Chapter 12

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 12 Array

  2. Convert Numbers in Different Base Systems • Generate values to a series of numbers in different base systems: • Base is between 2 and 9; • Maximum number of digits is 100. • Number is NOT in reverse order! • Example: • 3 1201 • Value = 1*33 + 2*32 + 0*3 + 1 = 46 How do we know how many digits a number have? Use Array!

  3. Convert Numbers in Different Base Systems const int MAX_DIGIT = 100; const char ZERO = '0‘; int base, counter, size = 0, numValue = 0; char chDigit; int number[MAX_DIGIT]; cin >> base >> chDigit; while ( chDigit != '\n' ) { number[size] = chDigit - ZERO; size ++; cin.get(chDigit); } cout << endl << "Given base " << base << ", the decimal value of "; for ( counter = 0; counter < size; counter ++ ) { numValue += number[counter] * pow ( base, size - counter - 1 ); cout << number[counter]; } cout << " is " << numValue << "."; return 0; // declare an array // for loop

  4. floating address float double long double pointer reference C++ Data Types simple structured integral enum array struct union class char short int long bool

  5. One-Dimensional Array • A one-dimensional array is a structured collection of components (array elements) that can be accessed individually by specifying the position of a component with a single index value. • An array is a homogeneous data structure: • All components are of the same data type • A component of an array is accessed by its position in the structure.

  6. Highest, Lowest and Average of 100 Scores float score; float total, max, min, avg; intscoreCount; // Using one variable to input and process scores // One score at a time // When do we need to keep all scores? // Is my score below or above the average? // How do we keep all scores? // Array!

  7. Declaration of Variables intscoreCount; float score, total; char grade; string courseName; boolvalidInput; // Memory Allocation // Address for each variable // Size for each data type // int : 2 bytes // float : 4 bytes // char : 1 byte // string: # of chars plus one

  8. Declaration of Arrays • Syntax: • Example: float scores[100]; // 100 floats char chs[20]; // 20 chars intnums[30]; // 30 integers string allNames[100]; // 100 strings bool prog3Completed[26]; // 26 bool values DataTypeArrayName [ConstantExpression];

  9. Memory Allocation for Array intnums[30]; // 30 integers // Address: the first element’s address // How many bytes? // 30 * 2: 60 bytes nums Address: 7000 7002 7004 7006 7056 7058 The base address of an array is its beginning address in memory.

  10. Array Size Must Be Constant Expressions constint MAX_SIZE = 30; int size = 30; intnums[30]; float ArrayA[MAX_SIZE]; // Valid? // Yes! // number of bytes? float ArrayB[size]; // Valid? // NO! float ArrayC[MAX_SIZE * 10]; // Valid? // Yes! // number of bytes? However, no magic number in your programs!

  11. Array Element and Array Index int nums[30]; Array Element 0 1 2 3 28 29 Array Indices Array Element nums[0] nums[1] nums[29]

  12. Array Element and Array Index • How to access array elements? • Use array index to specify array element. int value = num[3]; cout << value; // we get 50! • Index of any array begins with 0! • Never go out of the array boundary! • Exercise: int m = 2; what is num[m+1]? what is num[m]+1?

  13. Operations on Array Elements • An array element is the same as a single variable. • Operations on array elements: Input Output Arithmetic operations Assignment Comparison Function parameters …

  14. Example: Operations on Array Elements intnums[30]; // Read an integer and store it in the 1st element of nums. cin >> nums[0]; // Incement the 1st element of nums by one. nums[0] ++; // Assign the value of the 1st element of nums to // the 2nd element of nums. nums[1] = nums[0]; // Incement the 2nd element of nums by the value of size. nums[1] += size; // Set the last element of nums to the value of size. nums[29] = size; // Assign the value of the 16th element of nums to size. size = nums[15];

  15. Example: Operations on Array Elements intnums[30]; // Display 1st element of nums with a width of 9. cout << endl << setw(9) << nums[0]; // Compute the average of the 1st and last elements of // nums and store it in avg. avg = (nums[0] + nums[29]) / 2.0; // If the 2nd element is not zero, display the float // quotient of 1st element divided by 2nd. if (nums[1] != 0) cout << "Quotient = " << float(nums[0]) / nums[1]; // Call function Largest to find the max value between // the first three elments of nums and store it in Max. // Function prototype: // int Largest(int num1, int num2, int num3); Max = Largest(nums[0], nums[1], nums[2]);

  16. Exercise constint MAX_SIZE = 30; intnums[MAX_SIZE], index; cin >> nums[29]; // Valid. cin >> nums[30]; // Not Valid! Out of Boundary Error! cout << nums[MAX_SIZE - 1]; // Valid. cout << nums[MAX_SIZE]; // Not Valid! Out of Boundary Error! cin >> index; if (index < MAX_SIZE && index >= 0) nums[index] = nums[10]; // Valid.

  17. Assign Values to An Array • Initializing arrays in declarations. int age[5] = {23, 19, 33, 45, 60}; float temperature[] = {0.0, 112.37, -12, 98.6}; • in C++, you are allowed to omit the size of an array when initializing it! • The compiler figures out the size by itself! • Use loop to assign values to an array. int age[5]; int index = 0; while ( index < 5 ) { cin >> age[index]; index ++; } int i; for (i = 0; i < 5; i ++ ) cin >> age[i]; for loop is a better way to handle arrays!

  18. For Loop • Syntax: • Initialization is an assignment statement; • Condition is a logic expression; • Update is an incrementing or decrementing statement. • Compare with while loop: for ( Initialization; Condition; Update ) { loop body; } Initialization; while ( condition ) { loop body; update; }

  19. Translate between while and for loops Calculate the sum of 1 to 10: int total = 0; int num; for ( num = 1; num <= 10; num ++ ) { total += num; } int total = 0; int num = 1; while ( num <= 10 ) { total += num; num ++; }

  20. Use for loop to handle arrays • You MUST use for loop to handle arrays if possible! • You can use i, j, kas the LCV in for loops without violating the variable naming rule. int ArrayA[30], size, j; cin >> size; // Assume size is between 1 and 30 // Input to an array for (int i = 0; i < size; i ++) cin >> ArrayA[i]; // Output array for (j = 0; j < size; j ++) cout << endl << setw(8) << ArrayA[j];

  21. Highest, Lowest and Average of 100 Scores float score[NUM_SCORE]; float total = 0, max = 0, min = 0, avg, index; for (int i = 0; i < NUM_SCORE; i++) { cin >> score[i]; if ( max < score[i] || i == 0) max = score[i]; if ( min > score[i] || i == 0) min = score[i]; total += score[i]; } avg = total / NUM_SCORE; cout << “\nThe average score of the “ << NUM_SCORE << “ scores is “ << avg << endl; cout << “Please enter your score ID: “; cin >> index; cout << endl << “You score is ” << score[index] << “.“; // what is the scope of i? // within the for loop! // because it is declared // in the for statement.

  22. Passing arrays as function parameters • Basic Data Types (char, int, float, string, bool) Pass by Value (without &) Pass by Reference (with &) • Arrays (of any data type) Always Pass by Reference (Never &) The base address of the array is sent to the function! • Why? Save Space and Time for copying values

  23. Using a function to read data to an array The size (number of elements) is known Function Prototype Function Name InputToArray Function Type void //How to return an array? Parameters s[] : array of float In, Out, InOut OUT size: int, number of elements of s[] In, Out, InOut IN // Parameters: (Out, In) void InputToArray(float s[], int size); // No &!

  24. Using a function to read data to an array //-------------------------------------------------- // The function reads size float values into // array s[], assuming size is positive // and in the range. // Parameters: (out, in) //-------------------------------------------------- void InputToArray(float s[], int size) { for (int i = 0; i < size; i++) cin >> s[i]; } // What’s the value of size?

  25. Using a function to read data to an array const int MAX_SIZE = 100; void InputToArray(float s[], int size); int main() { int count; float scores[MAX_SIZE], average; cout << "Please enter the size of the array: "; cin >> count; // Call function to input data to array Scores[] InputToArray(scores, count); // No [] for array as actual parameter // No type for any actual parameters return 0; }

  26. Passing arrays as IN parameters • Basic Data Types (char, int, float, string, bool) Pass by Value (without &) In Parameters Pass by Reference (with &) Out and InOut Parameters • Arrays (of any data type) Always Pass by Reference (Never &) In Parameters: const • const is used to prevent the function from modifying the caller’s array value.

  27. Using a function to compute average The size (number of elements) is known Function Prototype Function name ArrayAvg Function type float Parameters s[] : array of float In size: int, number of elements of s[] In // Parameters: (In, In) float ArrayAvg(const float s[], int size); // Array is always passed by reference // Use const for In array parameter // No const for size

  28. Using a function to compute average //------------------------------------------------------ // The function computes and returns the average of all // array elements of s[], assuming size is positive // and in the range. // Parameters: (In, In) //------------------------------------------------------ float ArrayAvg ( const float s[], int size ) { float total; total = 0; for (int i = 0; i < size; i++) total += s[i]; return total / size; } // Compute average after the for loop. // Not inside the loop!

  29. Using a function to compute average const int MAX_SIZE = 100; void InputToArray(float s[], int size); float ArrayAvg(const float s[], int size); int main() { int count; float Scores[MAX_SIZE], average; cout << "Please input the size of the array: "; cin >> count; InputToArray(Scores, count); // Function call: No type! No []! average = ArrayAvg(Scores, count); // Function call: No type! No []! cout << “The average score: “ << average; return 0; }

  30. Passing arrays as function parameters • IN parameter: float ArrayAvg(const float s[], int size); • must use const • no &! • OUT and INOUT parameters: void InputArray(float s[], int size); • no &! • Function call: InputToArray(Scores, count); average = ArrayAvg(Scores, count); • no [ ], & or data type!

  31. Read value and size of an array //-------------------------------------------------- // The function reads float values into array s[] and // count the actual size of s[]. User stops inputting // by entering -1. Once the user input maxSize elements, // the function will stop reading the input. // Parameters: (out, out, in) //-------------------------------------------------- void InputSizeAndValues(float s[], int& size, int maxSize) { size = 0; cin >> s[size]; while ( s[size] != -1 && size < maxSize ) { size ++; cin >> s[size]; } return; } // What’s the value of size? if we have constant MAX_SIZE, do we still need this parameter?

  32. Linear Search • Is a value in the array? • Where is the Maximum/Minimum element in the array?

  33. Find a target in an array void InputToArray(float s[], int& size); int main() { int count; float MyArray[50], target; InputToArray(MyArray, count);// Assume count is 8 // Is 51 in the array? // Is 60 in the array? cin >> target; // Linear search! return 0; } 0 1 2 3 4 5 6 7 49

  34. Linear Search Function: Find Target in an Array The function returns true if target is found in the array, false otherwise. Function Prototype Function Name SearchArray FindTarget or Find Function Type bool (true/false) Function parameters floatArray[]: array of type float size : int, number of elements of floatArray target : a float number //In, Out, InOut? // Parameters: In, In, In boolSearchArray(const float floatArray[], int size, float target);

  35. //-------------------------------------------------------------------//------------------------------------------------------------------- // The function has three parameters: // floatArray[]: array of type float // size : int, number of elements of floatArray // target : a float number // The function returns true if target is found in floatArray, // false otherwise. // Parameters: (in, in, in) //------------------------------------------------------------------- boolSearchArray(const float floatArray[], int size, float target) { for (int i = 0; i < size; i++) { if (floatArray[i] == target) return true; else // ? } // When to return false? return false; } 0 1 2 3 4 5 6 7

  36. //------------------------------------------------ // The function has three parameters: // floatArray[]: array of type float // size : int, number of elements of // floatArray // target : a float number // The function returns a bool value: // true if target is found in floatArray, // false otherwise. // Parameters: (in, in, in) //------------------------------------------------ boolSearchArray(const float floatArray[], int size, float target) { for (int i = 0; i < size; i++) { if (floatArray[i] == target) return true; } return false; }

  37. const int MAX_SIZE = 50; void InputSizeAndValues ( float s[], int& size, intmaxSize ); boolSearchArray ( const float floatArray[], int size, float target ); int main() { float MyArray[MAX_SIZE], target; int count; InputSizeAndValues(MyArray, count, MAX_SIZE); cin >> target; while (!cin.eof()) { if ( SearchArray( MyArray, count, target ) ) cout << "Value " << target << " is in the array."; else cout << "Value " << target << " is NOT in the array."; cin>> target; } return 0; }

  38. Where is the target in the array? //------------------------------------------------ // The function has three parameters: // floatArray[]: array of type float // size : int, number of elements of // floatArray // target : a float number // The function returns the index of the target // if target is found in floatArray, -1 otherwise. // Parameters: (in, in, in) //------------------------------------------------ intSearchArray( const float floatArray[], int size, float target) { for (int i = 0; i < size; i++) { if (floatArray[i] == target) return i; } return -1; }

  39. Linear Search • Is a value in the array? • Check array elements one at a time until • target is found or • all array elements have been checked • What is the Maximum/Minimum element in the array? • Assign the first element to max; • Compare max with every array element and update max until all array elements have been compared with

  40. Find the Largest Value of All Array Elements Function Prototype Function Name MaxArrayValue Function Type int (float) Same as the array type Function parameters s[] : array of int size : int, number of elements in s[] //In, Out, InOut? // Parameters: (in, in) int MaxArrayValue(const int s[], int size);

  41. //-----------------------------------------------------------//----------------------------------------------------------- // The function has two parameters: // s[]: array of float // size : int, number of elements in s[] // The function finds and returns the largest array element // of s[], assuming size is positive and in the range. // Parameters: (in, in) //----------------------------------------------------------- float MaxArrayValue(const float s[], int size) { int max; max = s[0]; for (int i = 1; i < size; i ++) if (s[i] > max) max = s[i]; return max; }

  42. //-----------------------------------------------------------//----------------------------------------------------------- // The function has two parameters: // s[]: array of float // size : int, number of elements in s[] // The function finds and returns the largest array element // of s[], assuming size is positive and in the range. // Parameters: (in, in) //----------------------------------------------------------- float MaxArrayValue(const float s[], int size) { int max; max = s[0]; for (int i = 0; i < size; i ++) if (s[i] > max) max = s[i]; return max; } //Correct? //Good? Yes. No. Extra comparison: s[0] v.s. s[0]

  43. //-----------------------------------------------------------//----------------------------------------------------------- // The function has two parameters: // s[]: array of int // size : int, number of elements in s[] // The function finds and returns the largest array element // of s[], assuming size is positive and in the range. // Parameters: (in, in) //----------------------------------------------------------- float MaxArrayValue(const float s[], int size) { int max; max = 0; for (int i = 0; i < size; i ++) if (s[i] > max) max = s[i]; return max; } //Correct? //No! What if all elements are negative?

  44. Parallel Arrays • Different arrays sharing the same index. • Student records: • Student ID • First name • Last name • Gender • major • GPA

  45. Student Records Const int MAX_STUDENTS = 100; long id [MAX_STUDENTS]; string firstName[MAX_STUDENTS]; string lastName [MAX_STUDENTS]; char gender [MAX_STUDENTS]; string major [MAX_STUDENTS]; float gpa [MAX_STUDENTS]; // Given the student ID, how to output one student’s complete record?

  46. Search and Output a Student Record • Algorithm: • Read student records into arrays from an input file • Read a student ID • Search for the ID, if it exists: • Find the rest of the student record and print them out • Otherwise, tell the user this record does not exist. 1. When reading parallel arrays, keep their index the same! 2. Linear search: return the index of the target student ID! 3. Use the returned index to find the rest parts of a record, because they share the same index!

  47. Read Student Records From a File Function Prototype Function Name ReadRecord Function Type int Function parameters maxSize : int, maximum number of student records to handle id : long array of student ID firstName: string array of first names lastName: string array of last names gender: character array of student genders major: string array of student majors gpa: float array of student gpa //In, Out, InOut? // Parameters: (in, out, out, out, out, out, out ) • int ReadRecord ( int maxSize, long id[], • string firstName[], string lastName[], • char gender[], string major[], • float gpa[] );

  48. Read Records From Input File //-------------------------------------------------------------- // The function reads student records from an input file into // different arrays and count the actual number of input records. // Once the user input maxSize elements, the function will stop // reading the input. It returns the actual number of records. // Parameters: (in, out, out, out, out, out, out) //-------------------------------------------------- int ReadRecord ( int maxSize, long id[], string firstName[], string lastName[], char gender[], string major[], float gpa[] ) { ifstreaminData; inData.open ( "student-record.in" ); int size = 0; inData >> id[size] >> firstName[size] >> lastName[size] >> gender[size] >> major[size] >> gpa[size]; while ( !inData.eof() && size < maxSize ) { size ++; inData >> id[size] >> firstName[size] >> lastName[size] >> gender[size] >> major[size] >> gpa[size]; } inData.close(); return size; } // We will talk about file stream later. // Keep index the same!

  49. Search for ID //------------------------------------------------ // The function has three parameters: // myArray[] : array of type long // size : int, number of elements of // myArray // target : a long number // The function returns the index of the target // in the array if it is found; -1 otherwise. // Parameters: (in, in, in) //------------------------------------------------ int SearchID ( const long myArray[], int size, long target ) { for ( int i = 0; i < size; i++ ) { if ( myArray[i] == target ) return i; } return -1; } // The returned index is used to // locate other parts of a record!

  50. Output a Student Record Function Prototype Function Name OutputRecord Function Type void Function parameters stuID: long, student ID size : int, total number of student records id : long array of student ID firstName: string array of first names lastName: string array of last names gender: character array of student genders major: string array of student majors gpa: float array of student gpa //In, Out, InOut? // Parameters: (in, in, in, in, in, in, in, in ) void OutputRecord ( longstuID, int size, const long id, const string firstName, const string lastName, const char gender, const string major, const float gpa);

More Related