1 Arrays and Strings Chapter 9 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : 85 79 92 57 68 80... 0 1 2 3 4 5 98.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Copyright © 2002 Pearson Education, Inc. Slide 1.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
Chapter 4 Parameters and Overloading. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Learning Objectives Parameters Call-by-value Call-by-reference.
Chapter 1 C++ Basics. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 1-2 Learning Objectives Introduction to C++ Origins, Object-Oriented.
Chapter 9 – One-Dimensional Numeric Arrays. Array u Data structure u Grouping of like-type data u Indicated with brackets containing positive integer.
Writing Pseudocode And Making a Flow Chart A Number Guessing Game
Problem Solving & Program Design in C
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 11: Structure and Union Types Problem Solving & Program Design.
Programming Language Concepts
Chapter 7: Arrays In this chapter, you will learn about
1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure Definitions 10.3Initializing Structures 10.4Accessing.
Chapter 17 Linked Lists.
1 Arrays … The Sequel Applications and Extensions Chapter 10.
Modern Programming Languages, 2nd ed.
2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Structures, Unions, Bit Manipulations, and Enumerations Outline 10.1Introduction 10.2Structure.
1 What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight.
1 Records C++ Structs Chapter 14 2 What to do with records?  Declaring records  Accessing records  Accessing the field of a record  What is a union?
LO: Count up to 100 objects by grouping them and counting in 5s 10s and 2s. Mrs Criddle: Westfield Middle School.
1 Variables and Data Types. 2 Variable Definition a location in memory, referenced by a name (identifier), where data of a given type can be stored, changed,
Before Between After.
CS 240 Computer Programming 1
Model and Relationships 6 M 1 M M M M M M M M M M M M M M M M
EC-111 Algorithms & Computing Lecture #11 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
Pointers and Arrays Chapter 12
PSSA Preparation.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 16P. 1Winter Quarter Strings Lecture 16.
User Defined Functions Lesson 1 CS1313 Fall User Defined Functions 1 Outline 1.User Defined Functions 1 Outline 2.Standard Library Not Enough #1.
Getting Data into Your Program
Data Structures Using C++ 2E
Strings.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 10.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
1 September 6, 2005CS150 Introduction to Computer Science I What Actions Do We Have Part 1 CS150 Introduction to Computer Science I.
Chapter 9: Arrays and Strings
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 8 Arrays and Strings
String What it is Why it’s useful library routines for handling strings how to input a string from the keyboard.
Basic Elements of C++ Chapter 2.
UNFORMATTED INPUT OUTPUT. Topics to be discussed……………….. overloaded operators >> and and
Expressions and Interactivity Chapter 3. 2 The cin Object Standard input object Like cout, requires iostream file Used to read input from keyboard Often.
In Addition... To the string class from the standard library accessed by #include C++ also has another library of string functions for C strings that can.
1 Data Structures A Data Structure is an arrangement of data in memory. A Data Structure is an arrangement of data in memory.  The purpose is to map real.
Chapter 8 Arrays and Strings
C Programming Lecture 10 Instructor: Wen, Chih-Yu Department of Electrical Engineering National Chung Hsing University.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
1 Program Input Software Design Chapter 4. 2 You Will Want to Know... Prompting for and reading values into a program. Accessing data from a file. What.
1 Character Strings (Cstrings) Reference: CS215 textbook pages
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Copyright © 2006 Pearson Addison-Wesley. All rights reserved This Weeks Topics: Pointers (continued)  Modify C-String through a function call 
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
C++ Programming Lecture 14 Arrays – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
1 Applied Arrays Lists and Strings Chapter 12 2 Applying What You Learn Searching through arrays efficiently Sorting arrays Using character arrays as.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
1 Chapter 7 Pointers and C-Strings. 2 Objectives  To describe what a pointer is (§7.1).  To learn how to declare a pointer and assign a value to it.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
Basic Elements of C++.
Basic Elements of C++ Chapter 2.
Input and Output Chapter 3.
Arrays and Strings Chapter 9.
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Presentation transcript:

1 Arrays and Strings Chapter 9

2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting arrays Stepping through arrays Passing arrays as parameters

3 Design Problem l Consider a program to calculate class average Why?? ?

4 Add to Design Problem l Now your client says, I need to ALSO calculate and display “deviations” from the average Describe why this will or will NOT work

5 l Enter in the scores again l Use 100 separate variables » and cout and cin commands l Read (then re-read) from a file l The real answer … Possible Solutions  Use arrays !!  

6 Simple vs Structured Data Types l Simple data type => data element contains a single value l Structured data type => a data element contains a collection of data values x : 15 avg : ch : ‘A’ scores : name : ‘C’ ‘L’ ‘Y’ ‘D’ ‘E’

7 Arrays l Arrays are Structured Data Types l They have a means of accessing individual components l Values can be retrieved from and stored in the structure scores : cout << scores[2]; scores[0] = 100;

8 One Dimensional Array l Structured collection of components » All of the same type l Structure given a single name l Individual elements accessed by index indicating relative position in collection l Type of elements stored in an array can be “just about” anything l Index of an array must be an integer

9 Use of Array for Our Problem l Store elements in array as read in l Go back and access for deviations Note declaration

10 Declaring Arrays l Syntax: Data_type Array_name [constant]; l Note declaration from our example Tells how many elements set aside

11 Declaring Arrays l Example specifies an array… » each element is an integer » there is space for 100 elements » the are numbered 0 through 99 scores :

12 Accessing Individual Components l Use the name of the array l Followed by an integer expression inside the square brackets [ ] scores : max = scores[0]; for (x = 0; x max) max = scores[x]; Index can be: - constant - variable - expression MUST be an integer

13 Out of Bounds Index l What happens if … l C++ does NOT check for index out of range l Possible to walk off into “far reaches” of memory -- clobbers... » other variable locations ».exe code » the operating system (??) float f_list [50]; f_list [100] = ; float f_list [50]; f_list [100] = ;

14 Initializing Arrays in Declarations l Possible to declare the size & initialize l Possible to omit size at declaration » Compiler figures out size of array int results [5] = {14, 6, 23, 8, 12 } float prices [ ] = { 2.41, 85.06, 19.95, 3.91 }

15 Aggregate Operations l Defn => an operation on the data structure as a whole » as opposed to operation on a SINGLE element within the structure l Example » would be nice to read in a WHOLE array

16 Lack of Aggregate Operations l Would be nice but... C++ does NOT have... l Assignment operator for whole array l Arithmetic operations for whole array (think matrix) l Comparisons for arrays (not even = =) l Return of an array type by a function

17 How to Accomplish Aggregate Operations? l Most such tasks (assignment, read, write) can be performed some other way » CS II course will write “classes” to provide these functions l Otherwise » these operations must be performed by the programmer » element by element in a loop

18 Arrays as Parameters l This is one task that CAN be done to the WHOLE array l C++ always passes arrays by reference

19 Arrays as Parameters l The name of the array is a pointer constant l The address of the array is passed to the function l Size of the array also passed to control loop

20 Arrays as Parameters l Note the empty brackets in parameter list » A number can be placed here but it will be ignored

21 Sub-array Processing l Note we specified an array size of 100 » but we don’t anticipate that many scores l Array always declared larger than needed l Must keep track of how many have been used » this is our limit when doing other things to the array

22 C-Strings or Character Arrays l We have learned that the elements of an array can be just about anything l Consider an array whose elements are all characters » Called a C-String » Has a collection of special routines » Treated differently for I/O than other types of arrays

23 Declaration of C-Strings Similar to declaration of any array char name[30]; // no initialization char title [20] = "Le Grande Fromage"; // initialized at declaration // with a string char chList [10] = {'a', 'b', 'c', 'd'}; // initialized with list of char // values

24 Working with Character Strings l String => a collection of characters interpreted as a single item » a structured data item » in C++ a null-terminated sequence of characters stored in a char array l All strings in C++ are terminated by the null character » character 0, ‘\0’

25 Initializing Strings l When a character array is declared, it is legal to use the assignment operator to initialize l Note : use of the = operator only legal for char array initialization l But : aggregate array assignment is NOT greeting = “don’t do it;

26 String Output l Strings (character arrays) are handled differently than other types of arrays l This would NOT be allowed l This is legal: int num_list [100];... cout << num_list; char name [30] = “Snidly Q. Fizbane”;... cout << name;

27 String Input l Declare strings 1 element bigger than planned size to allow for ‘\0’ l When input takes place, C++ automatically places the ‘\0’ in memory at the end of the characters typed in

28 Problems with >> for String Input l Cannot be used to input a string with imbedded blanks l >> stops reading as soon as it encounters first whitespace character

29 Problems with >> for String Input Solve problem by using getline ( … ) Quits reading after 15 characters or when it hits a newline, whichever comes first. Includes all characters including spaces, tabs, etc (whitespace characters)

30 Problems with >> for String Input l If declared string is too small >> keeps putting characters in memory PAST that area in memory s2 contents extend into the memory area of s3

31 Using Strings Instead of “hard coding” file name for the open ( … ) command, » use a string variable, » use keyboard entry with cin.getline(…) » program more flexible, good for different files ifstream inFile; char fname[31]; cout “; cin.getline (fname, 30, ‘\n’); inFile.open (fname);

32 String Library Routines l Recall that we could not use the aggregate assignment of one string to another l C++ provides some string handling functions to do this (and other similar tasks) l Found in or

33 Contrast/Compare Strings and C-Strings Assignment is OK string s; s = "hi mom"; Comparison OK if (s < "geek") … I/O allowed cin >> s; cin.getline(s,'\n'); cout << s; Assignment is illegal char cs[30]; cs = "don't do it"; l Comparisons not allowed l I/O allowed much the same way

34 Working with C-Strings Functions provided in #include Used instead of assignment Used for comparisons

35 Another Problem l Some functions require C-strings as parameters » The.open() command for files The.open() command for files l C-strings are terminated by the null character (character 0) » Such functions are looking for that l String objects are built differently

36 Solving the File Open Problem l One of the functions available for a string object will convert it to a C-String The function is c_str() l Remember that string functions are called by using » The variable » The member operator var.c_str() » The name of the function l View example View example

37 Design Problem l Consider the task of keeping track of data about parts for manufacture » part number, description, qty needed, unit price

38 Design Problem l Use “Parallel” arrays l One array each for part num, descrip, qty, price l n th item in any one of the arrays associated with same n th item of all the arrays part #descripqtyprice A100xxx B25yyy

39 Testing and Debugging Hints l Range of legal index values is 0 to array_size - 1 l Individual elements of the array are of the component type l No aggregate operations in arrays » you must write the code to do this l If array parameter is incoming, specify formal parameter as const » prevents function from modifying

40 Testing and Debugging Hints l Omitting array size in declaration » when array declared formal parameter » when array initialized at declaration l Don’t pass component when function expects entire array l Declare array size as max ever needed » process only part of array which is used l Pass array name and length to functions which process array or sub array

41 Testing and Debugging l Be sure to account for null character when you manipulate characters individually in a string l Remember proper use of the = » correct for initialization at declarationtime » INCORRECT for aggregate assignment l Aggregate input/output allowed for strings but NOT for other array types

42 Testing and Debugging l If you use the >> for string input, make sure » string is declared large enough » string will have no white spaces l The >> operator stops at, but does not consume the first trailing white space » such as ‘\n’ or a space l The cin.getline (whatever, 30, ‘\n’ ) function » stops when reading the ‘\n’ » consumes the ‘\n’ » has problems when ‘\n’ is still in the input stream

43 Testing and Debugging When using the strcpy ( ), make sure that the destination array is declared long enough l Choose test data carefully for string handling programs » include strings that are too large » include strings with whitespace