Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315.

Slides:



Advertisements
Similar presentations
1 Arrays Chapter 9. 2 Outline  The array structure (Section 9.1)  Array declaration  Array initialization  Array subscripts  Sequential access to.
Advertisements

Chapter 7: User-Defined Functions II
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Chapter 04 (Part III) Control Statements: Part I.
Lecture 2 Introduction to C Programming
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.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
1 The first step in understanding pointers is visualizing what they represent at the machine level. In most modern computers, main memory is divided into.
Arrays.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
CMSC 104, Version 8/061L22Arrays1.ppt Arrays, Part 1 of 2 Topics Definition of a Data Structure Definition of an Array Array Declaration, Initialization,
Arrays One-Dimensional initialize & display Arrays as Arguments Part I.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 2 Introduction to C++
 2006 Pearson Education, Inc. All rights reserved Arrays.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
A First Book of ANSI C Fourth Edition
Copyright © 2002 W. A. Tucker1 Chapter 7 Lecture Notes Bill Tucker Austin Community College COSC 1315.
CHAPTER 07 Arrays and Vectors (part I). OBJECTIVES 2 In this part you will learn:  To use the array data structure to represent a set of related data.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
C++ Programming: Basic Elements of C++.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 11 Structured Data.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Arrays Arrays in C++ An array is a data structure which allows a collective name to be given to a group of elements which all have.
CS102 Introduction to Computer Programming Chapter 9 Pointers.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11: Structured Data.
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)
A first program 1. #include 2. using namespace std; 3. int main() { 4. cout
Copyright © 2012 Pearson Education, Inc. Chapter 11: Structured Data.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 8 Arrays.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
CHAPTER 6 ARRAYS IN C++ 2 nd Semester King Saud University College of Applied studies and Community Service CSC 1101 By: Fatimah Alakeel Edited.
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.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
CHAPTER 2 PART #3 C++ INPUT / OUTPUT 1 st Semester King Saud University College of Applied studies and Community Service CSC1101 By: Fatimah.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and 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.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 11: Structured Data.
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Dr. Yang, QingXiong (with slides borrowed from Dr. Yuen, Joe) LT:10 Advance Pointer Array, String and Dynamic Memory Allocation CS2311 Computer Programming.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Lecture 8 – Array (Part 1) FTMK, UTeM – Sem /2014.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Chapter Structured Data 11. Combining Data into Structures 11.2.
Lecture 2 Arrays. Topics 1 Arrays hold Multiple Values 2 Accessing Array Elements 3 Inputting and Displaying Array Contents 4 Array Initialization 5 Using.
1 Principles of Computer Science I Honors Section Note Set 3 CSE 1341.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Data Storage So far variables have been able to store only one value at a time. What do you do if you have many similar values that all need to be stored?
Objectives You should be able to describe: One-Dimensional 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.
Bill Tucker Austin Community College COSC 1315
Bill Tucker Austin Community College COSC 1315
New Structure Recall “average.cpp” program
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Arrays, For loop While loop Do while loop
One-Dimensional Array Introduction Lesson xx
7 Arrays.
7 Arrays.
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
Fundamental Programming
CS150 Introduction to Computer Science 1
Presentation transcript:

Copyright © 2002 W. A. Tucker1 Chapter 9 Lecture Notes Bill Tucker Austin Community College COSC 1315

Copyright © 2002 W. A. Tucker2 Multiple Values Recall that every value stored in memory needs an identifier (name) to refer to the contents of the memory location What if you have multiple values of the same data type EX:Five Integers –int num1, num2, num3, num4, num5;

Copyright © 2002 W. A. Tucker3 Processing Multiple Values If you wanted to read in the five values and average them, here is the code: int num1, num2, num3, num4, num5; int sum, avg; cout << “Enter 5 integers “; cin >>num1>>num2>>num3>>num4>>num5; sum = num1+num2+num3+num4+num5; avg = sum / 5; cout << “Sum is “<<sum<<“ Avg is “<<avg<<endl; Note that there is a unique identifier for each Now what if you had fifty values?? Or 500??

Copyright © 2002 W. A. Tucker4 Arrays An Array is a collection of data elements What is a collection? –A stamp collection is a collection of stamps –A coin collection is a collection of coins –A doll collection is a collection of dolls They all have something in common Thus an Array is a collection of data elements of the same data type

Copyright © 2002 W. A. Tucker5 Array Declarations Arrays are declared as follows: –To declare an array (collection) of data types use: int num [50];// arrray of integers double value [10];// array of doubles char letter [26];// array of characters bool test [15];// array of boolean values string name [25];// array of strings Thus you only have one identifier to represent 50 different values How does the compiler know which entry in the array you want to use??

Copyright © 2002 W. A. Tucker6 Array Subscripts Array subscripts are used to indicate specific elements of an array In mathematics, X 2 is read as “X sub 2” In C++, x [ 2 ] is read as “X sub 2” A subscript may even contain expressions X [ y + 3] Array subscripts MUST be an integer value

Copyright © 2002 W. A. Tucker7 Array Addressing Elements refer to the number of different values that may be in an array Subscripts refer to a specific addressable value An array declared as: int num [5]; contains 5 elements num[0] num[1] num[2] num[3] num[4] The valid subscripts are 0 through 4 Note for an array of “SIZE”, the valid subscripts are “ZERO” through “SIZE – 1”

Copyright © 2002 W. A. Tucker8 Array Addressing Example Given the array int num [5]; num[3] = 6;// will assign a 6 to subscript 3 num[4] = 2;// will assign a 2 to subscript 4 num[0] = 8; // will assign an 8 to subscript 0 num[1] = 3;// will assign a 3 to subscript 1 num[2] = 5;// will assign a 5 to subscript 2 Elements Size Elements Value Subscript (Size-1) sub

Copyright © 2002 W. A. Tucker9 Subscript Range C++ does not do error checking on the value of a subscript Valid subscripts are zero though size-1 If you try to address a subscript outside the range of zero through size-1 you will not get an error message from C++ BUT you may create a catastrophic error and get “this program has performed an illegal operation and will be shut down” The statement num[-1] = 0; will store a zero in the location BEFORE the start of array num

Copyright © 2002 W. A. Tucker10 Subscript = Memory Address Normally the compiler knows the memory address of a variable name An array uses subscripts to determine which element in the array is being addressed –This subscript may be the result of a calculation, there is no way the compiler may determine the location –The compiler generates code that computes the memory location during execution

Copyright © 2002 W. A. Tucker11 Array Memory Mapping Since an array is a collection of elements of the same data type, the size (number of bytes) of each element is known by the compiler The name of the array equates to a specific memory address (the address where the array starts) The value of the subscript is used to calculate a “displacement” or “offset” from the array address to determine the exact memory address

Copyright © 2002 W. A. Tucker12 Memory Mapping Example An integer usually occupies 4 bytes Given: int num[5]; Element Subscript Offset Memory * * * * 4 30C *

Copyright © 2002 W. A. Tucker13 Accessing Array Elements Repetition logic is well suited to access array values since they only have one identifier Read and average 5 integer values int num[5], avg, sum = 0; for (int i=0; i<5; i++) { cout << “Enter an integer “; cin >> num[i]; sum = sum + num[i]; } avg = sum / 5; cout << “Sum is “<< sum << “ Avg is “ << avg << endl;

Copyright © 2002 W. A. Tucker14 More on Declaring Arrays Note that the for loop used the array size of 5 in the test If we write a program for a particular array size, then need to change the size, there are many places to change code An easier way is to declare a constant integer called SIZE and use that in both the declaration and loop

Copyright © 2002 W. A. Tucker15 Example of Averaging Array Values const int SIZE = 5; int num[SIZE]; int avg, sum = 0; for (int i=0; i < SIZE; i++) { cout << “Enter an integer “; cin >> num[i]; sum = sum + num[i]; } avg = sum / SIZE; cout << “Sum is “ << sum << “ Avg is “ << avg << endl;

Copyright © 2002 W. A. Tucker16 Initializing Arrays Recall that declaration statement have the option to initialize values This is also true when declaring arrays int num[5] = {8, 3, 5, 6, 2}; int num[5] = {0, 0, 0, 0, 0}; What will the following do? a) int num[5] = {0};// declaration b) for (int i=0; i<5; i++)// execution num[i] = 0;

Copyright © 2002 W. A. Tucker17 Passing Arrays to Functions An array name passed as an argument to a function is automatically passed by reference –To pass by value would require making a copy of the entire array This is indicated with the addition of square braces [ ] in both the prototype and function header, but NOT in the function call Since the function needs to know the size of the array, passing the array size makes it possible to write generic functions that process arrays

Copyright © 2002 W. A. Tucker18 Function to Sum an Array Prototype:int sumArray (int [ ], int); Declaration: int num[10], result; Call: result = sumArray (num, 10); Definition: int sumArray (int a[ ], int size} { int sum = 0; for (int i = 0; i < size; i++) sum = sum + a[i]; return sum; }

Copyright © 2002 W. A. Tucker19 Passing One Value of an Array You can also pass just one value of an array to a function, just like it was a single identifier Prototype: void display (int); Declaration: int num[10]; Call: display (num[3]); Definition void display (int x) { cout <<“Value is “ << x << endl; }

Copyright © 2002 W. A. Tucker20 Summary of Array Passing Passing an integer array called num Prototype Call Definition int [ ] (num) int a [ ] Passing a value of an integer array called num Prototype Call Definition int (num[i]) int a

Copyright © 2002 W. A. Tucker21 Parallel Arrays Recall that an array is a collection of elements related by the same data type. How can you establish an array relationship of sets of elements where each set contains more than one data type? The answer is to utilize the concept of “parallel arrays.”

Copyright © 2002 W. A. Tucker22 Parallel Arrays Parallel Arrays are different arrays that have the same number of entries. Since they are different arrays, they may contain collections of different data types. Since they have the same number of elements, there is a correspondence relationship between elements with the same subscript

Copyright © 2002 W. A. Tucker23 Parallel Arrays EX: a set of two data elements that are related, Student ID Student Grade int studID[SIZE];double studGrade[SIZE]; Subscript N

Copyright © 2002 Jade Lindquist24 Iterating through Parallel Arrays Code to print the contents of two parallel arrays: int studID[SIZE]; double studGrade[SIZE]; int cnt = 0; getInput(ifile, studID, studGrade, cnt ); // cnt is set to the number of elements read into the array for (int i = 0; i < cnt; i++) { cout << “Student ID: “ << studID[i] << “ Grade: “ << studGrade[i] << endl; }

Copyright © 2002 Jade Lindquist25 Filling arrays from a file Code to fill the two parallel arrays from a file: int studID[SIZE]; double studGrade[SIZE]; int cnt = 0; // cnt of records in the file while (cnt < SIZE && !ifile.eof()) { ifile >> studID[cnt] >> studGrade[cnt]; cnt++; }

Copyright © 2002 Jade Lindquist26 The count of records in the arrays should be passed to any function that operates on the arrays. Filling arrays from a file, cont.

Copyright © 2002 Jade Lindquist27 Input Files When reading from a file using the extraction operator (>>), delete any blank lines and spaces at the end of your last record. Example: The cursor should be immediately after the 1. Otherwise, your program may read in garbage data.

Copyright © 2002 Jade Lindquist28 Input Files When reading from a file using getline, end your last line of data with a new line. The cursor should be at the beginning of the line AFTER your last record. Example: The quick brown fox jumped over the lazy dog. Now is the time for all good men to come to the aid of your country. She sells sea shells by the sea shore. Inch by inch, life's a cinch. Yard by yard, life is hard. The cursor should be under the ‘I’ in “Inch”. Otherwise, your program will not read the last record.