Lecture 14: Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.

Slides:



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

Starting Out with C++, 3 rd Edition 1 Chapter 9 – Pointers.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
1 11/8/06CS150 Introduction to Computer Science 1 Arrays Chapter 8 page 477 November 13, 2006.
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based.
Chapter 7 Arrays C++ Programming, Namiq Sultan1 Namiq Sultan University of Duhok Department of Electrical and Computer Engineering Reference: Starting.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
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.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Introduction to Arrays. Useful Array Operations  Finding the Highest Value int [] numbers = new int[50]; int highest = numbers[0]; for (int i = 1; i.
CS102 Introduction to Computer Programming Chapter 7 Arrays.
Lecture 18: Structured Data Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Chapter 8 Arrays and Strings
Lecture 16: Searching and Sorting Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
Lecture 6: Expressions and Interactivity (Part II) Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
ARRAYS Lecture 2. 2 Arrays Hold Multiple values  Unlike regular variables, arrays can hold multiple values.
Value and Reference Parameters. CSCE 1062 Outline  Summary of value parameters  Summary of reference parameters  Argument/Parameter list correspondence.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
Lecture 8: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Lecture: Arrays. 7.1 Arrays Hold Multiple Values.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Lecture 7: Making Decisions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Lecture 9: Making Decisions Final Section Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.
 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.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
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.
Starting Out with C++: From Control Structures through Objects
Starting Out with C++, 3 rd Edition Introduction to the STL vector The Standard Template Library (or STL) is a collection of data types and algorithms.
Lecture 5: Expressions and Interactivity Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
11 PART 2 ARRAYS. 22 PROCESSING ARRAY ELEMENTS Reassigning Array Reference Variables The third statement in the segment below copies the address stored.
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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 7: Arrays.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Functions BICSE-6A Mr. Naeem Khalid Lecturer, Dept. of Computing.
STARTING OUT WITH STARTING OUT WITH Class 2 2 Review of course requirements: Homework due Thursday at beginning of class-- no lates accepted Programs.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1.
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
Copyright © 2012 Pearson Education, Inc. Chapter 7: Arrays.
Lecture 12: Functions Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220.
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
Copyright © 2013 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Third Edition by Tony Gaddis.
ARRAYS (C) KHAERONI, M.SI. OVERVIEW Introduction to Arrays Arrays in Functions Programming with Arrays Multidimensional Arrays.
Chapter 7: Arrays. 7.1 Arrays Hold Multiple Values.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Arrays Hold Multiple Values 7.1.
Chapter 8: Arrays. Arrays Hold Multiple Values Array: variable that can store multiple values of the same type Values are stored in adjacent memory locations.
Beginning C for Engineers Fall 2005 Arrays, 2-D arrays, character strings Bettina Schimanski Lecture 5: Section 2 (9/28/05) Section 4 (9/29/05)
Objectives You should be able to describe: One-Dimensional Arrays
Starting Out with C++, 3 rd Edition 1 Chapter 7 – Arrays.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Lecture 6 Arrays and Vectors
Chapter 7: Arrays.
Chapter 7 – Arrays.
Week 13 & 14 Arrays SCK1213Programming Technique I SEM1 2009/2010
New Structure Recall “average.cpp” program
Multi-dimensional Array
Chapter 7: Arrays.
7 Chapter Arrays.
Starting Out with Programming Logic & Design
Arrays Arrays A few types Structures of related data items
Presentation transcript:

Lecture 14: Arrays Professor: Dr. Miguel Alonso Jr. Fall 2008 CGS2423/COP1220

Processing Array Contents Concept: Individual array elements are processed like any other type of variable Don’t confuse with this pay = hours[3] * rate; int score[5] = {7, 8, 9, 10, 11}; ++score[2]; score[4]++; amount[count--]; amount[count]--;

// This program stores, in an array, the hours worked by // employees who all make the same hourly wage. #include using namespace std; int main() { const int NUM_EMPLOYEES = 5; int hours[NUM_EMPLOYEES]; double payrate; // Input the hours worked. cout << "Enter the hours worked by "; cout << NUM_EMPLOYEES << " employees who all\n"; cout << "earn the same hourly rate.\n"; for (int index = 0; index < NUM_EMPLOYEES; index++) { cout << "Employee #" << (index + 1) << ": "; cin >> hours[index]; } // Input the hourly rate for all employees. cout << "Enter the hourly pay rate for all the employees: "; cin >> payrate; // Display each employee's gross pay. cout << "Here is the gross pay for each employee:\n"; cout << fixed << showpoint << setprecision(2); for (index = 0; index < NUM_EMPLOYEES; index++) { double grossPay = hours[index] * payrate; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; } return 0; }

Invalid array assignment The following statement is not valid The only way to assign one array to another is to assign the individual elements in the arrays, usually done with a loop const in SIZE=4; int oldValues[SIZE] = {10, 100, 200, 300}; int newValues[SIZE]; newValues = oldValues; for(int count = 0; count < SIZE; count++) { newValues[count]=oldValues[count]; }

The reason that this does not work is that when the array name is used without brackets and subscript, it is seen as the array’s beginning memory address

Printing the Contents of an Array This will display the array’s beginning memory address, not the contents of the array You must use a loop to display the contents The only exception is when you are displaying the contents of a char array that contains a C-string const int SIZE = 5; int array[SIZE] = {10, 20, 30, 40, 50}; cout << array << endl; // This is wrong! char name[ ] = “Ruth”; cout << name << endl;

Thing we can do with arrays // summing the values in the array const int NUM_UNITS = 24; int units[NUM_UNITS]; int total = 0; // Initialize accumulator for (int count = 0; count < NUM_UNITS; count++) { total+= units[count]; } // averaging the values in the array const int NUM_SCORES = 10; double scores[NUM_SCORES]; double total = 0; // Initialize accumulator double average; // Will hold the average for (int count = 0; count < NUM_UNITS; count++) { total+= scores[count]; } average = total / NUM_SCORES; // Find the highest/lowest vaules const int SIZE = 50; int numbers[SIZE]; // numbers must contain data int count; int highest; highest = numbers[0]; for (count = 1; count < size; count++) { if(numbers[count] > highest) highest = numbers[count]; }

// This program reads data from a file into an array. #include using namespace std; int main() { const int ARRAY_SIZE = 100; // Array size int numbers[ARRAY_SIZE]; // Array with 100 elements int count = 0; // Loop counter variable ifstream inputFile; // Input file stream object inputFile.open("numbers.txt"); // Open the file. // Read the numbers from the file into the array. // After this loop executes, the count variable will hold // the number of values that were stored in the array. while (count > numbers[count]) count++; // Close the file. inputFile.close(); // Display the numbers read. cout << "The numbers are: "; for (int index = 0; index < count; index++) cout << numbers[index] << " "; cout << endl; return 0; }

Comparing Arrays You cannot compare two arrays by comparing their names, you must compare them element by element.

Using Parallel Arrays Concept: By using the same subscript, you can build relationships between data stored in two or more arrays // This program uses two parallel arrays: one for hours // worked and one for pay rate. #include using namespace std; int main() { const int NUM_EMPLOYEES = 5; // Number of employees int hours[NUM_EMPLOYEES]; // Holds hours worked double payRate[NUM_EMPLOYEES]; // Holds pay rates // Input the hours worked and the hourly pay rate. cout << "Enter the hours worked by " << NUM_EMPLOYEES << " employees and their\n" << "hourly pay rates.\n"; for (int index = 0; index < NUM_EMPLOYEES; index++) { cout << "Hours worked by employee #" << (index+1) << ": "; cin >> hours[index]; cout << "Hourly pay rate for employee #" << (index+1) << ": "; cin >> payRate[index]; } // Display each employee's gross pay. cout << "Here is the gross pay for each employee:\n"; cout << fixed << showpoint << setprecision(2); for (int index = 0; index < NUM_EMPLOYEES; index++) { double grossPay = hours[index] * payRate[index]; cout << "Employee #" << (index + 1); cout << ": $" << grossPay << endl; } return 0; }

Arrays as Function Arguments Concept: To pass an array as an argument to a function, pass the name of the array When a single element of an array is passed to a function, it is handled like any other variable // This program demonstrates that an array element is passed // to a function like any other variable. #include using namespace std; void showValue(int); // Function prototype int main() { const int SIZE = 8; int numbers[SIZE] = {5, 10, 15, 20, 25, 30, 35, 40}; for (int index = 0; index < SIZE; index++) showValue(numbers[index]); return 0; } //********************************************** // Definition of function showValue. * // This function accepts an integer argument. * // The value of the argument is displayed. * //********************************************** void showValue(int num) { cout << num << " "; } // This program demonstrates an array being passed to a function. #include using namespace std; void showValues(int [], int); // Function prototype int main() { const int ARRAY_SIZE = 8; int numbers[ARRAY_SIZE] = {5, 10, 15, 20, 25, 30, 35, 40}; showValues(numbers, ARRAY_SIZE); return 0; } //************************************************** // Definition of function showValue. * // This function accepts an array of integers and * // the array's size as its arguments. The contents * // of the array are displayed. * //************************************************** void showValues(int nums[], int size) { for (int index = 0; index < size; index++) cout << nums[index] << " "; cout << endl; }

// This program demonstrates the showValues function being // used to display the contents of two arrays. #include using namespace std; void showValues(int [], int); // Function prototype int main() { const int SIZE1 = 8; // Size of set1 array const int SIZE2 = 5; // Size of set2 array int set1[SIZE1] = {5, 10, 15, 20, 25, 30, 35, 40}; int set2[SIZE2] = {2, 4, 6, 8, 10}; // Pass set1 to showValues. showValues(set1, SIZE1); // Pass set2 to showValues. showValues(set2, SIZE2); return 0; } //************************************************** // Definition of function showValues. * // This function accepts an array of integers and * // the array's size as its arguments. The contents * // of the array are displayed. * //************************************************** void showValues(int nums[], int size) { for (int index = 0; index < size; index++) cout << nums[index] << " "; cout << endl; } // This program uses a function to double the value of // each element of an array. #include using namespace std; // Function prototypes void doubleArray(int [], int); void showValues(int [], int); int main() { const int ARRAY_SIZE = 7; int set[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7}; // Display the initial values. cout << "The arrays values are:\n"; showValues(set, ARRAY_SIZE); // Double the values in the array. doubleArray(set, ARRAY_SIZE); // Display the resulting values. cout << "After calling doubleArray the values are:\n"; showValues(set, ARRAY_SIZE); return 0; } //***************************************************** // Definition of function doubleArray * // This function doubles the value of each element * // in the array passed into nums. The value passed * // into size is the number of elements in the array. * //***************************************************** void doubleArray(int nums[], int size) { for (int index = 0; index < size; index++) nums[index] *= 2; } //************************************************** // Definition of function showValues. * // This function accepts an array of integers and * // the array's size as its arguments. The contents * // of the array are displayed. * //************************************************** void showValues(int nums[], int size) { for (int index = 0; index < size; index++) cout << nums[index] << " "; cout << endl; }

// This program gets a series of test scores and // calculates the average of the scores with the // lowest score dropped. #include using namespace std; // Function prototypes void getTestScores(double[], int); double getTotal(double[], int); double getLowest(double[], int); int main() { const int SIZE = 4; // Array size double testScores[SIZE], // Array of test scores total, // Total of the scores lowestScore, // Lowest test score average; // Average test score // Set up numeric output formatting. cout << fixed << showpoint << setprecision(1); // Get the test scores from the user. getTestScores(testScores, SIZE); // Get the total of the test scores. total = getTotal(testScores, SIZE); // Get the lowest test score. lowestScore = getLowest(testScores, SIZE); // Subtract the lowest score from the total. total -= lowestScore; // Calculate the average. Divide by 3 because // the lowest test score was dropped. average = total / (SIZE - 1); // Display the average. cout << "The average with the lowest score " << "dropped is " << average << ".\n"; return 0; } //******************************************************** ** // The getTestScores module accepts an array and its size * // as arguments. It prompts the user to enter test scores, * // which are stored in the array. * //******************************************************** ** void getTestScores(double scores[], int size) { // Loop counter int index; // Get each test score. for(index = 0; index <= size - 1; index++) { cout << "Enter test score number " << (index + 1) << ": "; cin >> scores[index]; } //**************************************************** // The getTotal function accepts a double array * // and its size as arguments. The sum of the array's * // elements is returned as an double. * //**************************************************** double getTotal(double array[], int size) { double total = 0; // Accumulator // Add each element to total. for (int count = 0; count < size; count++) total += array[count]; // Return the total. return total; } //**************************************************** // The getLowest function accepts a double array and * // its size as arguments. The lowest value in the * // array is returned as an double. * //**************************************************** double getLowest(double array[], int size) { double lowest; // To hold the lowest value // Get the first array's first element. lowest = array[0]; // Step through the rest of the array. When a // value less than lowest is found, assign it // to lowest. for (int count = 1; count < size; count++) { if (array[count] < lowest) lowest = array[count]; } // Return the lowest value. return lowest; }

Col 0Col 1Col 2 Row 0scores[0][0]scores[0][1]scores[0][2] Row 1scores[1][0]scores[1][1]scores[1][2] Two-Dimensional Arrays Concept: A two-dimensional array is like several identical arrays put together. It is useful for storing multiple sets of data So far the arrays we have seen are one- dimensional double scores[2][3]; RowsCols

// This program demonstrates a two-dimensional array. #include using namespace std; int main() { const int NUM_DIVS = 3; // Number of divisions const int NUM_QTRS = 4; // Number of quarters double sales[NUM_DIVS][NUM_QTRS]; // Array with 3 rows and 4 columns. double totalSales = 0; // To hold the total sales. int div, qtr; // Loop counters. cout << "This program will calculate the total sales of\n"; cout << "all the company's divisions.\n"; cout << "Enter the following sales information:\n\n"; // Nested loops to fill the array with quarterly // sales figures for each division. for (div = 0; div < NUM_DIVS; div++) { for (qtr = 0; qtr < NUM_QTRS; qtr++) { cout << "Division " << (div + 1); cout << ", Quarter " << (qtr + 1) << ": $"; cin >> sales[div][qtr]; } cout << endl; // Print blank line. } // Nested loops used to add all the elements. for (div = 0; div < NUM_DIVS; div++) { for (qtr = 0; qtr < NUM_QTRS; qtr++) totalSales += sales[div][qtr]; } cout << fixed << showpoint << setprecision(2); cout << "The total sales for the company are: $"; cout << totalSales << endl; return 0; }

Initializing 2D arrays int hours[3][2] = { {8, 5}, {7, 9}, {6, 3} }; int hours[3][2] = {{8, 5}, {7, 9}, {6, 3} }; int hours[3][2] = {8, 5, 7, 9, 6, 3 }; int hours[3][2] = { {1}, {3, 4}, {5} };

Passing 2D arrays to Functions When a two dimensional array is passed to a function, the parameter type must contain a size declarator for the number of columns The function can accept any two-dimensional integer array, as long as it consists of four columns void showArray(int [ ][COLS], int)

// This program demonstrates accepting a 2D array argument. #include using namespace std; // Global constants const int COLS = 4; // Number of columns in each array const int TBL1_ROWS = 3; // Number of rows in table1 const int TBL2_ROWS = 4; // Number of rows in table2 void showArray(int [][COLS], int); // Function prototype int main() { int table1[TBL1_ROWS][COLS] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int table2[TBL2_ROWS][COLS] = {{10, 20, 30, 40}, {50, 60, 70, 80}, {90, 100, 110, 120}, {130, 140, 150, 160}}; cout << "The contents of table1 are:\n"; showArray(table1, TBL1_ROWS); cout << "The contents of table2 are:\n"; showArray(table2, TBL2_ROWS); return 0; } //***************************************************************** // Function Definition for showArray * // The first argument is a two-dimensional int array with COLS * // columns. The second argument, rows, specifies the number of * // rows in the array. The function displays the array's contents. * //***************************************************************** void showArray(int array[][COLS], int rows) { for (int x = 0; x < rows; x++) { for (int y = 0; y < COLS; y++) { cout << setw(4) << array[x][y] << " "; } cout << endl; }

Summing elements in two- dimensional array Use nested for loops to access the elements in the rows and columns SEE examples on pg

Arrays of Strings Concept: A two-dimensional array of characters can be used as an array of strings char scientists[4][9] = {“Galileo”, “Kepler”, “Newton”, “Einstein” }; for (int count = 0; count < 4; count++) { cout << scientists[count] << endl; }

// This program displays the number of days in each month. #include using namespace std; int main() { const int NUM_MONTHS = 12; // The number of months const int STRING_SIZE = 10; // Maximum size of each string // Array with the names of the months char months[NUM_MONTHS][STRING_SIZE] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; // Array with the number of days in each month int days[NUM_MONTHS] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Display the months and their numbers of days. for (int count = 0; count < NUM_MONTHS; count++) { cout << months[count] << " has "; cout << days[count] << " days.\n"; } return 0; }

Arrays with Three or More Dimensions Concept: C++ does not limit the number of dimensions that an array may have. It is possible to create arrays with multiple dimensions, to model data that occur in multiple sets. double seats[3] [5] [8];

Case Study // This program is a driver that tests a function comparing the // contents of two int arrays. #include using namespace std; // Function Prototype bool testPIN(int [], int [], int); int main () { const int NUM_DIGITS = 7; // Number of digits in a PIN int pin1[NUM_DIGITS] = {2, 4, 1, 8, 7, 9, 0}; // Base set of values. int pin2[NUM_DIGITS] = {2, 4, 6, 8, 7, 9, 0}; // Only 1 element is // different from pin1. int pin3[NUM_DIGITS] = {1, 2, 3, 4, 5, 6, 7}; // All elements are // different from pin1. if (testPIN(pin1, pin2, NUM_DIGITS)) cout << "ERROR: pin1 and pin2 report to be the same.\n"; else cout << "SUCCESS: pin1 and pin2 are different.\n"; if (testPIN(pin1, pin3, NUM_DIGITS)) cout << "ERROR: pin1 and pin3 report to be the same.\n"; else cout << "SUCCESS: pin1 and pin3 are different.\n"; if (testPIN(pin1, pin1, NUM_DIGITS)) cout << "SUCCESS: pin1 and pin1 report to be the same.\n"; else cout << "ERROR: pin1 and pin1 report to be different.\n"; return 0; } //****************************************************************** // The following function accepts two int arrays. The arrays are * // compared. If they contain the same values, true is returned. * // If the contain different values, false is returned. * //****************************************************************** bool testPIN(int custPIN[], int databasePIN[], int size) { for (int index = 0; index < size; index++) { if (custPIN[index] != databasePIN[index]) return false; // We've found two different values. } return true; // If we make it this far, the values are the same. }