Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS 1400 Chapter 7 ARRAYS. Array variables Simple variables can hold single values int x;// x can hold one integer float y; // y can hold one float Array.

Similar presentations


Presentation on theme: "CS 1400 Chapter 7 ARRAYS. Array variables Simple variables can hold single values int x;// x can hold one integer float y; // y can hold one float Array."— Presentation transcript:

1 CS 1400 Chapter 7 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 xyzw

3 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! z 0 1 2 3 4 5592156

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

5 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}; z 0 1 2 3 4 3344551122 1.0 0.0 0.0 w 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!! 0 1 2 3 4 5 6 … cost These cells belong to costWho 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… 1.Read in the correct answers array from “key.txt” 2.Read in student’s answers from “answers.txt” 3.Compare against correct answers and determine score 4.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++; 4. 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 with size elements: 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:partcost 413121.78 21422.98 456234.56 7869.56 17786.99 356198.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… 1.read database into parallel arrays. 2.query user for part number and quantity 3.use a linear search to find associated cost 4.calculate order total 5.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); Arrays are always passed by reference

25 Arrays as function parameters Array parameters are declared with empty brackets; A function with an array parameter usually needs 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 char arrays revisited… Again, char arrays are handled in a special way for input and output. On input, the system will store a NULL character ‘\0’ at the end of a string On output, the system will output chars until the NULL character is encountered

29 Example; char word[10]; cin >> word; cout << “The word is: “ << word << endl; 0 1 2 3 4 5 6 7 8 9 word Fred\0

30 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; 67.8361.9959.70 44.5642.6839.98 89.9983.5680.15 55.6751.3449.99 Covering material Style 0 1 2 01230123

31 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];

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

33 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];

34 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

35 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];

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


Download ppt "CS 1400 Chapter 7 ARRAYS. Array variables Simple variables can hold single values int x;// x can hold one integer float y; // y can hold one float Array."

Similar presentations


Ads by Google