1 Arrays and Strings Lecture: 25 19.09.2012 2 Design Problem l Consider a program to calculate class average Why?? ?

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

1 Arrays and Strings Chapter 9 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
TK1914: C++ Programming Array II. Objective In this chapter you will explore how to manipulate data in a two-dimensional array. 2FTSM :: TK1914,
Chapter 10.
Computer Science 1620 Loops.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 Lecture 21:Arrays and Strings(cont.) Introduction to Computer Science Spring 2006.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
1 Arrays In many cases we need a group of nearly identical variables. Example: make one variable for the grade of each student in the class This results.
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.
 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
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
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.
Arrays (Part II). Two- and Multidimensional Arrays Two-dimensional array: collection of a fixed number of components (of the same type) arranged in two.
Prepared by MURLI MANOHAR PGT (COMPUTER SCIENCE) KV,B.E.G., PUNE.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
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.
Arrays One-Dimensional initialize & display Arrays as Arguments Part I.
 2006 Pearson Education, Inc. All rights reserved Arrays.
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.
EGR 2261 Unit 9 Strings and C-Strings  Read Malik, pages in Chapter 7, and pages in Chapter 8.  Homework #9 and Lab #9 due next week.
1 C++ Syntax and Semantics, and the Program Development Process.
C++ PROGRAMMING: PROGRAM DESIGN INCLUDING DATA STRUCTURES, FIFTH EDITION Chapter 10: Strings and string type.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Arrays  Array is a collection of same type elements under the same variable identifier referenced by index number.  Arrays are widely used within programming.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Arrays. Related data items Collection of the same types of data. Static entity – Same size throughout program.
1 One Dimensional Arrays Chapter 11 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores :
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.
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.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
Review Pointer Pointer Variables Dynamic Memory Allocation Functions.
Arrays.
Module 1: Array ITEI222 - Advance Programming Language.
Opening Input/Output Files ifstream infile; ofstream outfile; char inFileName[40]; char outFileName[40]; coutinFileName;
Programming Fundamentals. Today’s Lecture Array Fundamentals Arrays as Class Member Data Arrays of Objects C-Strings The Standard C++ string Class.
Multidimensional Arrays tMyn1 Multidimensional Arrays It is possible to declare arrays that require two or more separate index values to access an element.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Chapter 9 Arrays. Chapter Objectives Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of “array index.
Chapter 9 Arrays. Chapter Objectives Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of “array index.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
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.
EGR 2261 Unit 10 Two-dimensional Arrays
EGR 2261 Unit 9 One-dimensional Arrays
Computer Programming BCT 1113
Arrays Arrays exist in almost every computer language.
Arrays and Strings Chapter 9.
7 Arrays.
7 Arrays.
Arrays Arrays A few types Structures of related data items
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.
Dr. Khizar Hayat Associate Prof. of Computer Science
Presentation transcript:

1 Arrays and Strings Lecture:

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

3 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

4 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 !!  

5 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’

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

7 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

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

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

10 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 :

11 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

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

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

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

15 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

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

17 Multidimensional Arrays l A collection of a fixed number of components arranged in two dimensions » All components are of the same type l The syntax for declaring a two-dimensional array is: dataType arrayName[intexp1][intexp2]; where intexp1 and intexp2 are expressions yielding positive integer values.

18 Multidimensional Arrays The two expressions intexp1 and intexp2 specify the number of rows and the number of columns, respectively, in the array l Two-dimensional arrays are sometimes called matrices or tables

19 Multidimensional Arrays double sales[10][5];

20 Accessing Array Elements l The syntax to access a component of a two- dimensional array is: arrayName[indexexp1][indexexp2] where indexexp1 and indexexp2 are expressions yielding nonnegative integer values indexexp1 specifies the row position and indexexp2 specifies the column position

21 Accessing Array Elements sales[2][3] = 35.60; 35.60

22 2-DIM. Array Initialization l Like one-dimensional arrays » Two-dimensional arrays can be initialized when they are declared l To initialize a two-dimensional array when it is declared 1. Elements of each row are enclosed within braces and separated by commas 2. All rows are enclosed within braces 3. For number arrays, if all components of a row are not specified, the unspecified components are initialized to zero

23 2-DIM. Array Initialization l Example: int anArray[3][5] = { { 1, 2, 3, 4, 5, }, // row 0 { 6, 7, 8, 9, 10, }, // row 1 { 11, 12, 13, 14, 15 } // row 2 };

24 2-DIM. Array Initialization l Accessing all of the elements of a two-dimensional array requires two loops: one for the row, and one for the column. l Since two-dimensional arrays are typically accessed row by row, generally the row index is used as the outer loop. for (int nRow = 0; nRow < nNumRows; nRow++) for (int nCol = 0; nCol < nNumCols; nCol++) cout << anArray[nRow][nCol];

25 Multidimensional Arrays l A collection of a fixed number of elements (called components) arranged in n dimensions (n >= 1) l Also called an n-dimensional array l General syntax of declaring an n-dimensional array is: dataType arrayName[intExp1][intExp2]...[intExpn]; where intExp1, intExp2, … are constant expressions yielding positive integer values Example: 3-Dimensional array: int anArray[5][4][3];

26 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

27 C-Strings or Character Arrays l Character array: An array whose components are of type char l String: A sequence of zero or more characters enclosed in double quote marks l C-stings are null terminated (‘\0’) l The last character in a string is the null character

28 C-Strings or Character Arrays char str[80] = “Amanuensis”

29 C-Strings or Character Arrays There is a difference between 'A' and "A" » 'A' is the character A » "A" is the string A Because strings are null terminated, "A" represents two characters, 'A' and '\0‘ Similarly, "Hello" contains six characters, 'H', 'e', 'l', 'l', 'o', and '\0'

30 C-Strings or Character Arrays l Consider the statement char name[16]; l Because C-strings are null terminated and name has sixteen components » the largest string that can be stored in name is 15 If you store a string of length, say 10 in name » the first 11 components of name are used and the last 5 are left unused

31 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

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

C-Strings: Example-1 #include using namespace std; int main() { const int MAX = 80; //maximum characters in a string char str[MAX]; //string variable str cout<< “Enter a string \n”; cin>>str; //put string in str cout<< “You entered: ” << str << endl; //display string from str getch(); return 0; } 33

Reading Embedded Blanks #include using namespace std; int main() { const int MAX = 80; char str[MAX]; cout<< “Enter a string \n”; cin.get(str,MAX); //member function get() of the stream class of // which cin is an object cout<< “You entered: ” << str << endl; getch(); return 0; } 34

Reading Multiple Lines #include using namespace std; const int MAX = 2000; char str[MAX]; int main() { cout<< “Enter a string \n”; cin.get(str, MAX, ‘$’); //terminate with $ cout<< “You entered: ” << str << endl; getch(); return 0; } 35

Copying a string: Hard-way #include #include // for copying a string #include using namespace std; int main() { char str1[] = “C++ is the best programming” “language that I have ever used.”; const int MAX = 80; char str2[MAX]; for(int j=0; j < strlen(str1); j++) str2[j] = str1[j]; cout<< str2 << endl; getch(); return 0; } 36

Copying a string: Easy-way #include #include // for copying a string #include using namespace std; int main() { char str1[] = “C++ is the best programming” “language that I have ever used.”; const int MAX = 80; char str2[MAX]; strcpy(str2, str1); cout<< str2 << endl; getch(); return 0; } 37

Standard C++ string Class 38 #include #include //string class #include using namespace std; int main() { string s1(“Man”); string s2 = “Beast”; string s3; s3 = s1; //assign cout << “s3 = “ << s3 << endl; s3 = “Neither “ + s1 + “ nor ”; //concatenate s3 += s2; //concatenate cout << “s3 = ” << s3 << endl; s1.swap(s2); //swap s1 and s2 cout << s1 << ” nor “ << s2 << endl; getch(); return 0; }

39 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

40 Working with Strings Functions provided in #include Used instead of assignment Used for comparisons

Working with Strings l C-strings are compared character by character using the collating sequence of the system l If we are using the ASCII character set 1. The string "Air" is smaller than the string "Boat" 2. The string "Air" is smaller than the string "An" 3. The string "Bill" is smaller than the string "Billy" 4. The string "Hello" is smaller than "hello" 41

Working with Strings 42

Passing Arrays to Functions Arrays can be used as arguments to functions. 43

Passing Arguments to Arrays #include using namespace std; int sum(int list[], int listSize) { int index, sum = 0; for(index=0; index<listSize; index++) sum = sum + list[index]; return sum; } int main() { int myArray[] = {2, 3, 5}; cout<< "The is: " << sum(myArray, 3); getch(); return 0; } 44