Arrays and Strings Chapter 9.

Slides:



Advertisements
Similar presentations
1 Arrays and Strings Chapter 9 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
Advertisements

Chapter 10.
Arrays Hanly - Chapter 7 Friedman-Koffman - Chapter 9.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Understanding Arrays and Pointers Object-Oriented Programming Using C++ Second Edition 3.
 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 9: Arrays and Strings
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
How to Program in C++ CHAPTER 3: INPUT & OUTPUT INSTRUCTOR: MOHAMMAD MOJADDAM.
Chapter 8 Arrays and Strings
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
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
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
 2003 Prentice Hall, Inc. All rights reserved. 1 Arrays Outline Introduction Arrays Declaring Arrays Examples Using Arrays.
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?? ?
 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.
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.
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)
CHAPTER 6 ARRAYS IN C 1 st semester King Saud University College of Applied studies and Community Service Csc 1101 F. Alakeel.
Slide 1 Chapter 9 Strings. Slide 2 Learning Objectives  An Array Type for Strings  C-Strings  Character Manipulation Tools  Character I/O  get, put.
4.1Introduction Arrays –Structures of related data items –Static entity (same size throughout program) A few types –Pointer-based arrays (C-like) –Arrays.
Introduction Programs which manipulate character data don’t usually just deal with single characters, but instead with collections of them (e.g. words,
Chapter Topics The Basics of a C++ Program Data Types
Chapter 7 Pointers and C-Strings
EGR 2261 Unit 10 Two-dimensional Arrays
EGR 2261 Unit 9 One-dimensional Arrays
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
Basic Elements of C++.
Arrays in C.
Basic Elements of C++ Chapter 2.
Input and Output Chapter 3.
Arrays … The Sequel Applications and Extensions
String in C++ A string is an array of characters which contains a non-printing null character ‘\0’ ( with ASCII value 0 ) marking its end. A string.
Object Oriented Programming COP3330 / CGS5409
7 Arrays.
Pointers, Dynamic Data, and Reference Types
Arrays Kingdom of Saudi Arabia
Week 9 – Lesson 1 Arrays – Character Strings
Review for Final Exam.
Today’s Lecture I/O Streams Tools for File I/O
Strings and Streams Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
String What it is Why it’s useful
Chapter 3 Input output.
Chapter 9 Strings Copyright © 2008 Pearson Addison-Wesley. All rights reserved.
CS150 Introduction to Computer Science 1
Review for Final Exam.
7 Arrays.
Arrays Arrays A few types Structures of related data items
An Introduction to Programming with C++ Fifth Edition
Chapter 1 c++ structure C++ Input / Output
Pointers, Dynamic Data, and Reference Types
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
4.1 Introduction Arrays A few types Structures of related data items
Chapter 12: More on C-Strings and the string Class
Presentation transcript:

Arrays and Strings Chapter 9

"All students to receive arrays!" reports Dr. Austin. Declaring arrays Passing arrays as parameters Stepping through arrays Inspecting arrays scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99

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

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

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

Simple vs Structured Data Types Simple data type => data element contains a single value Structured data type => a data element contains a collection of data values x : 15 avg : 84.35 ch : ‘A’ scores : 85 79 92 57 68 80 name : ‘C’ ‘L’ ‘Y’ ‘D’ ‘E’

Arrays Arrays are Structured Data Types They have a means of accessing individual components Values can be retrieved from and stored in the structure cout << scores[2]; scores[0] = 100; scores : 85 79 92 57 68 80 0 1 2 3 4 5

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

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

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

Declaring Arrays Example specifies an array… each element is an integer there is space for 100 elements the are numbered 0 through 99 scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99

Accessing Individual Components Use the name of the array Followed by an integer expression inside the square brackets [ ] scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99 Index can be: - constant - variable - expression MUST be an integer max = scores[0]; for (x = 0; x < 100; x++) if (scores[x] > max) max = scores[x];

Out of Bounds Index What happens if … C++ does NOT check for index out of range 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] = 123.456;

Initializing Arrays in Declarations Possible to declare the size & initialize 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 }

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

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

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

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

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

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

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

C-Strings or Character Arrays We have learned that the elements of an array can be just about anything 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

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

Working with Character Strings 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 All strings in C++ are terminated by the null character character 0, ‘\0’

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

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

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

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

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)

Problems with >> for String Input 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

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 << “Enter file name -> “; cin.getline (fname, 30, ‘\n’); inFile.open (fname);

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

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"; Comparisons not allowed I/O allowed much the same way

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

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

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

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

Design Problem Use “Parallel” arrays One array each for part num, descrip, qty, price nth item in any one of the arrays associated with same nth item of all the arrays part # descrip qty price A100 xxx 5 1.23 B25 yyy 23 8.95 1 2

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

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

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

Testing and Debugging If you use the >> for string input, make sure string is declared large enough string will have no white spaces The >> operator stops at, but does not consume the first trailing white space such as ‘\n’ or a space 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

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