array. convert numbers in different base systems generate values to a series of numbers in different...

53
Chapter 12 Array

Upload: cora-janney

Post on 22-Dec-2015

221 views

Category:

Documents


1 download

TRANSCRIPT

  • Slide 1
  • Array
  • Slide 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*3 3 + 2*3 2 + 0*3 + 1 = 46 How do we know how many digits a number have? Use Array!
  • Slide 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 > nums[0]; // Incement the 1 st element of nums by one. nums[0] ++; // Assign the value of the 1 st element of nums to // the 2 nd 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 16 th element of nums to size. size = nums[15];
  • Slide 15
  • Example: Operations on Array Elements int nums[30]; // Display 1 st element of nums with a width of 9. cout
  • Exercise const int MAX_SIZE = 30; int nums[MAX_SIZE], index; cin >> nums[29]; // Valid. cin >> nums[30]; // Not Valid! Out of Boundary Error! cout index; if (index = 0) nums[index] = nums[10]; // Valid.
  • Slide 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 ++; } for loop is a better way to handle arrays! int i; for (i = 0; i < 5; i ++ ) cin >> age[i];
  • Slide 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; }
  • Slide 19
  • Translate between while and for loops Calculate the sum of 1 to 10: int total = 0; int num = 1; while ( num
  • Use for loop to handle arrays You MUST use for loop to handle arrays if possible! You can use i, j, k as 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
  • 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
  • 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 > count; InputToArray(Scores, count); // Function call: No type! No []! average = ArrayAvg(Scores, count); // Function call: No type! No []! cout
  • 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; } // Whats the value of size? if we have constant MAX_SIZE, do we still need this parameter?
  • Slide 32
  • Linear Search Is a value in the array? Where is the Maximum/Minimum element in the array?
  • Slide 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; } 40455140 445950???.... ???? 0 1 2 3 4 5 6 7 49
  • Slide 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 bool SearchArray(const float floatArray[], int size, float target); 34
  • Slide 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) //------------------------------------------------------------------- bool SearchArray(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; } 40455140 445950???.... ???? 0 1 2 3 4 5 6 7
  • Slide 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) //------------------------------------------------ bool SearchArray(const float floatArray[], int size, float target) { for (int i = 0; i < size; i++) { if (floatArray[i] == target) return true; } return false; }
  • Slide 37 > target; } return 0; }">
  • const int MAX_SIZE = 50; void InputSizeAndValues ( float s[], int& size, int maxSize ); bool SearchArray ( 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 max) max = s[i]; return max; } //Correct? //Good? 42 Yes. No. Extra comparison: s[0] v.s. s[0]
  • Slide 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? 43
  • Slide 44
  • Parallel Arrays Different arrays sharing the same index. Student records: Student ID First name Last name Gender major GPA
  • Slide 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 students complete record?
  • Slide 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!
  • Slide 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[] );
  • Slide 48 > 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!">
  • 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[] ) { ifstream inData; 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!
  • Slide 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!
  • Slide 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 ( long stuID, int size, const long id, const string firstName, const string lastName, const char gender, const string major, const float gpa );
  • Slide 51
  • Output Record //------------------------------------------------------------------- // The function takes the student id and total number of records // as inputs. If there exists a record with that student id, // the function will print out the student's id, name, gender, major, // and gpa; otherwise, it will print a "Not found" message. // Parameters: (in, in, in, in, in, in, in, in ) //------------------------------------------------------------------- void OutputRecord ( long stuID, int size, const long id[], const string firstName[], const string lastName[], const char gender[], const string major[], const float gpa[] ) { int index; index = SearchID ( id, size, stuID ); if ( index != -1 ) { cout