1 / 34

CS 1400 March 5, 2007

CS 1400 March 5, 2007. Chapter 6 ARRAYS. Array variables. Simple variables can hold single values int x; // x can hold one integer float y; // y can hold one float Array variables can hold multiple values int z[5]; // z can hold 5 integers float w[3]; // w can hold 3 floats. x. y.

xia
Download Presentation

CS 1400 March 5, 2007

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. CS 1400March 5, 2007 Chapter 6 ARRAYS

  2. Array variables • Simple variables can hold single values int x; // x can hold one integer float y; // y can hold one float • Array variables can hold multiple values int z[5]; // z can hold 5 integers float w[3]; // w can hold 3 floats x y z w

  3. z 0 1 2 3 4 Array Access… • Individual cells of an array variable are accessed using an index: z[2] = 55; z[3] = 921; z[4] = z[2]+1; • Cells of an array are numbered beginning with zero! 55 921 56

  4. z 0 1 2 3 4 Array Indexes… • Array indexes can also be ordinal variables (integers) for (int n=0; n<5; n++) z[n] = n*10; 0 10 20 30 40

  5. 11 22 33 44 55 z 0 1 2 3 4 Array initialization… • Like simple variables, array variables can be intialized when declared: int z[5] = {11, 22, 33, 44, 55}; (If insufficient initializing constants are given, the rest default to zero.) float w[3] = {1.0}; w 1.0 0.0 0.0 0 1 3

  6. Array Examples • Declaration examples; int costs[10]; float rates[100]; int ages [n]; Can’t declare size with a variable! • Initialization examples; int costs [5] = {99, 88, 77, 66, 55}; float rates [100] = {1.0}; • References examples; costs[n] = 21; cout << rates[5]; ages[n]++; how is this different from ages[n++]?

  7. Array indexes… • Indexes may be constants (integers) or ordinal variables • Indexes may also be simple integer expressions; cout << costs[n+2]; • There is no array bounds checking. • Array cell indexes always start at 0 (zero) • In an executable statement, only array cells may be referenced costs = rates * 2; exception: char arrays holding words or strings exception: passing an array reference to a function

  8. No bounds checking? int cost[5]; for (int n=0; n<7; n++) cin >> cost[n]; // a long walk on a short pier!! cost … 0 1 2 3 4 5 6 … These cells belong to cost Who do these belong to?? other variables? program instructions?

  9. char arrays… • Note that char arrays are a special case! • can be input or output as “strings” char word[30]; cin >> word; • can also used as arrays if (word[0] == ‘a’) word[0] = ‘A’; cout << word[0] << word[5]; • can be inialized with strings or with characters char name[30] = “Bobby”; char name2[30] = {‘B’, ‘o’, ‘b’, ‘b’, ‘y’, ‘\0’};

  10. Example: test grading • Write a program to grade a test. A test has five (5) numeric answers. • assume: the test key is in key.txt • assume: the test is in answers.txt Example inputs: key.txt: 21 14 7 9 18 answers.txt: Fred 21 15 7 9 17 Example output: student: Fred score 3

  11. Pseudocode… • Read in the correct answers array from “key.txt” • Read in student’s answers from “answers.txt” • Compare against correct answers and determine score • Output student score

  12. 1. Read in correct answers int key[5]; ifstream fin_key; … fin_key.open (“e:\\key.txt”); for (int n=0; n<5; n++) fin_key >> key[n];

  13. 2. Read in student’s answers int answers[5]; char name[30]; ifstream fin_ans; … fin_ans.open (“e:\\answers.txt”); cin >> name; for (int n=0; n<5; n++) fin_ans >> answers[n];

  14. 3. Compare… int score = 0; … for (int n=0; n<5; n++) if (answers[n] == key[n]) score++; • Output score cout << “score is “ << score;

  15. int main() { int key[5], answers[5], score = 0; char name[30]; ifstream fin_key, fin_ans; fin_key.open (“e:\\key.txt”); for (int n=0; n<5; n++) fin_key >> key[n]; fin_ans.open (“e:\\answers.txt”); fin >> name; for (int n=0; n<5; n++) fin_ans >> answers[n]; for (int n=0; n<5; n++) if (answers[n] == key[n]) score++; cout << “score for “ << name << “ is “ << score << endl; }

  16. Linear Search • Search array list withsizeelements: find the position of variable value. bool found = false; int position = -1; for (int n=0; n<size && !found; n++) { if (list[n] == value) { position = n; found = true; } }

  17. Example using a linear search • Suppose a disk file contains a database of 100 part numbers and part costs: inventory.txt: part cost 413 121.78 214 22.98 456 234.56 786 9.56 177 86.99 356 198.22 …

  18. POS terminal program • Write a program to query the user for a part number and a quantity for an order. Calculate and display the total price of the order (including 20% markup and 6.5% sales tax) Enter part number and quantity: 177 32 Order total (including tax): $ 3557.54

  19. Pseudocode… • read database into parallel arrays. • query user for part number and quantity • use a linear search to find associated cost • calculate order total • display

  20. 1. Read database into parallel arrays int parts[100]; float costs[100]; char word[30]; ifstream fin; … fin.open (“inventory.txt”); fin >> word >> word; // skip over titles for (int n=0; n<100; n++) cin >> parts[n] >> costs[n];

  21. 2. Query user for part number and quantity int partnumber, quantity; … cout << “Enter part number and quantity: “; cin >> partnumber >> quantity;

  22. 3. Linear search… bool found = false; float thiscost = -1.0; … for (int n=0; n<100 && !found; n++) { if (partnumber == parts[n]) { found = true; thiscost = costs[n]; } }

  23. 4. Calculate total float total; … total = quantity * thiscost * 1.2 * 1.065; 5. Display cout << fixed << setprecision(2); cout << “Order total (including tax): $ “ << total;

  24. Passing Arrays to Functions… • Arrays (of any size) can be passed to functions by using just the array name as a function argument. float ages[100]; float weights[200] MyFunc(ages, 100); MyFunc(weights, 200);

  25. Arrays as function parameters • Array parameters are declared with empty brackets; • A function with an array parameter may need to know the size of the array or the number of elements to be considered; void MyFunc (float array[ ], int size); Array parameters are always reference parameters!

  26. Examples; • A function to find the maximum value of an array • A function to calculate the average value of an array • A function to count the number of negative values in an array

  27. Linear Search as a function… int LinearSearch (int list[], int size, int value) { bool found = false; int position = -1; for (int n=0; n<size && !found; n++) { if (list[n] == value) { position = n; found = true; } } return position; }

  28. Multi-dimension arrays • Arrays can contain sub-arrays. An array of rows of cells is a 2-d table: Consider a table of chair prices; Covering material 0 1 2 0 1 2 3 Style

  29. declaration with initialization… float chair_costs [4] [3] = {{ 67.83, 61.99, 59.70 }, { 44.56, 42.68, 39.98 }, { 89.99, 83.56, 80.15 }, { 55.67, 51.34, 49.99 }}; … int style, covering; cout << “enter a style and covering: “; cin >> style >> covering; cout << “cost is: “ << chair_costs[style] [covering];

  30. Passing multi-dimensional arrays • When passing a multi-dim. array, all but the first dimension of the corresponding parameter must be stated explicitly in main: cout << SumChairCosts (chair_costs) << endl; Function: float SumChairCosts (costs[ ] [3]) { float sum = 0; for (int row=0; row<4; row++) for (int col=0; col<3; col++) sum += costs[row][col]; return sum }

  31. Higher dimensioned arrays are possible, but rarely used • Consider a table of chairs • there are 4 styles • each style has 3 coverings • each covering has 5 colors • each color has 7 shades; float chair_costs [4] [3] [5] [7]; … int style, covering, color, shade; cout << “enter a style, covering, color and shade: “; cin >> style >> covering >> color >> shade; cout << “cost is: “ << chair_costs[style][covering][color][shade];

  32. 2-d char arrays • Since strings are stored in arrays of char, a 2-d char array is an array of strings! char names[5][10] = {“Fred”, “Jane”, “Billy”, “Annie”, “Jason”}; cout << names[n] << endl; // refers to row n or string n cout << names[n][m] << endl; // refers to char in row n, cell m for (int thisname = 0; thisname<5; thisname++) cin >> names[thisname]; // input 5 new names

  33. Common Errors… • Attempting to copy one array into another with a single assignment statement; • Taking a long walk on a short pier; int array1[10], array2[10]; array1 = array2; // illegal!! int array[10]; for (int n=0; n<=10; n++) // illegal!! cin >> array[n];

  34. Interesting questions… • Can an array have different kinds of cells? • Can an array size be changed while a program is running? • Can each row of a 2-d array have a different number of cells? • not yet…

More Related