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.

Slides:



Advertisements
Similar presentations
Making Choices in C if/else statement logical operators break and continue statements switch statement the conditional operator.
Advertisements

Chapter 10 Introduction to Arrays
Beginning C++ Through Game Programming, Second Edition by Michael Dawson.
Arrays. Topics Tables of Data Arrays – Single Dimensional Parsing a String into Multiple Tokens Arrays - Multi-dimensional.
Computer Science 1620 Loops.
1 CIS 205 Practice Test George Lamperti A word that has a predefined meaning in a C++ program and cannot be used as a variable name is known as.
CS 1400 Pick ups from chapters 4 and 5. if-else-if Chained if statements can be useful for menus… Enter savings plan choice: (A) economy rate (B) saver.
CS Oct 2006 Chap 6. Functions General form; type Name ( parameters ) { … return value ; }
CS 1400 Pick ups from chapters 4 and 5. if-else-if Chained if statements can be useful for menus… Enter savings plan choice: (A) economy rate (B) saver.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Computer Science 1620 Programming & Problem Solving.
1 Chapter 6 Looping Dale/Weems/Headington. 2 l Physical order vs. logical order l A loop is a repetition control structure based on a condition. l it.
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.
CS 1400 Chapters 9, 10 C-strings and Pointers. A few C-string library functions… #include int strcmp (char a[ ], char b[ ]); returns 0 if string a is.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Lesson 7 Arrays CS 1 Lesson 7 -- John Cole1. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 6 Looping.
Chapter 5: Control Structures II (Repetition)
CHAPTER 5: CONTROL STRUCTURES II INSTRUCTOR: MOHAMMAD MOJADDAM.
EGR 2261 Unit 5 Control Structures II: Repetition  Read Malik, Chapter 5.  Homework #5 and Lab #5 due next week.  Quiz next week.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
 2006 Pearson Education, Inc. All rights reserved Arrays.
Chapter 8 Arrays and Strings
1 Chapter 9 Additional Control Structures Dale/Weems/Headington.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Additional Control Structures. Chapter 9 Topics Switch Statement for Multi-way Branching Do-While Statement for Looping For Statement for Looping Using.
1 Chapter 9 Additional Control Structures Dale/Weems.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 5: Control Structures II (Repetition). Objectives In this chapter, you will: – Learn about repetition (looping) control structures – Learn how.
Chapter 7 Additional Control Structures. 2 2 void GetYesOrNo (/* out */ char& response) // Inputs a character from the user // Postcondition: response.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
1 Looping. 2 Chapter 6 Topics  While Statement Syntax  Phases of Loop Execution  Two Types of Loops: Count-Controlled Loops &Event-Controlled Loops.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
1 Arrays and Vectors Chapter 7 Arrays and Vectors Chapter 7.
1 Chapter 7 Arrays. 2 Topics 7.1 Arrays Hold Multiple Values 7.2 Accessing Array Elements 7.3 No Bounds Checking in C Array Initialization 7.5 Processing.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Before we get started…. First, a few things… Weighted Grading System Programming Style Submitting your assignments… The char and string variable types.
More Array Access Examples Here is an example showing array access logic: const int MAXSTUDENTS = 100; int Test[MAXSTUDENTS]; int numStudents = 0;... //
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Arrays Dr. Jose Annunziato. Arrays Up to this point we have been working with individual primitive data types Arrays allow working with multiple instances.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 7 Arrays.
1 Chapter 12 Arrays. 2 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating.
Chapter 15 Strings as Character Arrays
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Computer Programming for Engineers
Think First, Code Second Understand the problem Work out step by step procedure for solving the problem (algorithm) top down design and stepwise refinement.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
Chapter 7 Arrays Csc 125 Introduction to C++. Topics Arrays Hold Multiple Values Array Operations Arrays as function arguments Two-dimensional arrays.
Arrays Chapter 7. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
1 Programming in C++ Dale/Weems/Headington Chapter 6 Looping.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter 7 Pointers and C-Strings.
Array. Array is a group of data of the same type. Array elements have a common name –The array as a whole is referenced through the common name Individual.
Chapter 6 Looping. 2 l A loop is a repetition control structure. l it causes a single statement or block to be executed repeatedly What is a loop?
Objectives You should be able to describe: One-Dimensional Arrays
REPETITION CONTROL STRUCTURE
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
7 Arrays.
7 Arrays.
2008/11/19: Lecture 18 CMSC 104, Section 0101 John Y. Park
Presentation transcript:

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 variables can hold multiple values int z[5];// z can hold 5 integers float w[3];// w can hold 3 floats xyzw

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

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

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 w 0 1 3

Array Examples Declaration examples; const int SIZE = 10; int costs[SIZE]; 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++]?

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

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

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’};

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: answers.txt: Fred Jan Example output: student: Fred score 3 Jan score 4

Pseudocode… 1.Read in the correct answers array from “key.txt” 2.repeat for all students a)Read in student’s answers from “answers.txt” b)Compare against correct answers and determine score c)Output student score

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

2. Loop through all students char name[30]; ifstream fin_ans; … fin_ans.open (“e:\\answers.txt”); fin_ans >> name; while (!fin_ans.eof()) {… fin_ans >> name; }

a) read in student’s answers int answers[5]; … for (int n=0; n<5; n++) fin_ans >> answers[n];

b) compare… int score = 0; … for (int n=0; n<5; n++) if (answers[n] == key[n]) score++; c) output score cout << name << “ score “ << score << endl;

#include using namespace std; int main() {int key[5]; ifstream fin_key; int answers[5]; int score = 0; fin_key.open (“e:\\key.txt”);// read in correct answers for (int n=0; n<5; n++) fin_key >> key[n];

fin_ans.open (“e:\\answers.txt”); fin_ans >> name; while (!fin_ans.eof())// loop through all students { for (int n=0; n<5; n++) fin_ans >> answers[n]; // read in student’s answers for (int n=0; n<5; n++) if (answers[n] == key[n])// compare score++; cout << name << “ score “ << score << endl; fin_ans >> name; }

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

Example using a linear search Suppose a disk file contains a database of 100 part numbers and part costs: inventory.txt:partcost …

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: Order total (including tax): $

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

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++) fin >> parts[n] >> costs[n];

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

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

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

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

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!

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

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

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

Example; char word[10]; cin >> word; cout << “The word is: “ << word << endl; word Fred\0

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 Style

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

Passing multi-dimensional arrays When passing a multi-dim. array, all but the first dimension of the corresponding parameter must be stated explicitly in the receiving function 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 }

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

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

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

Example A file exists containing a row of daily rainfalls for each of 12 months (12 rows). Each row ends with -1 as a sentinel. For example; … Write a program to output a) the average rainfall for the year and b) the average rainfall for each month.

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…

Assignment Modify the previous Linear Searching program to add the options of adding and deleting employees. When an employee is added, a new line should be added to the database for the ID, extension, room, and department of that new employee. When an employee is deleted, the database line for that employee should be removed. HINT: Rather than delete a row in the parallel arrays of the database within the program, simply mark the ID as not used with a number like -1. Now, when searching the database, simply skip over the employees with IDs of -1. When the database is written back out to disk (at the end of the program), don’t write the lines for employees with IDs of -1.

Suggested menu: Enter choice:(E)mployee ID search (T)elephone extension search (R)oom number search (D)epartment code search (A)dd an employee de(l)ete an employee E(x)it program and update file:

Quiz Show the output of this segment int ages[4] = {21, 36}; for (int n=0; n<4; n++) cout << ages[n] << endl; for (int n=0; n<3; n++) ages[n+1] = ages[n] + 1; for (int n=0; n<4; n++) cout << ages[n] << endl;