CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare...

92
CHAPTER 9 ARRAYS AND STRINGS

Transcript of CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare...

Page 1: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

CHAPTER 9

ARRAYS AND STRINGS

Page 2: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

In this chapter, you will:•Learn about arrays•Explore how to declare and manipulate data into arrays•Understand the meaning of “array index out of bounds”•Become familiar with the restrictions on array processing

•Discover how to pass an array as a parameter to a function

•Learn about C-strings•Examine the use of string functions to process C-strings•Discover how to input data in—and output data from—a C-string

•Learn about parallel arrays

Page 3: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

• A data type is called simple if variables of that type can store only one value at a time.

• A structured data type is one in which each data item is a collection of other data items.

Page 4: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

//Program to read five numbers, find their sum, and //print the numbers in reverse order. 

#include <iostream>using namespace std; 

int main(){ int item0, item1, item2, item3, item4; int sum; 

cout<<"Enter five integers: "; cin>>item0>>item1>>item2>>item3>>item4; cout<<endl; 

sum = item0 + item1 + item2 + item3 + item4; 

cout<<"The sum of the numbers = "<<sum<<endl; cout<<"The numbers in reverse order are: "; cout<<item4<<" "<<item3<<" "<<item2<<" " <<item1<<" "<<item0<<endl; return 0;}

Page 5: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

We note the following in the above program. 1. Five variables must be declared because the numbers are to be

printed in reverse order.

2. All variables are of the type int—that is, of the same data type.

3. The way in which these variables are declared indicates that the variables to store these numbers have the same name except the last character, which is a number.

Statement 1 tells you that you have to declare five variables. Statement 3 tells you that it would be convenient if you could

somehow put the last character, which is a number, into a counter variable and use one for loop to count from 0 to 4 for reading and another for loop to count from 4 to 0 for printing.

All variables are of the same type. So you should be able to specify how many variables must be declared—and their data type—with a simpler statement than the one we used earlier.

Page 6: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Arrays An array is a collection of a fixed number of components wherein all

of the components are of the same data type. A one-dimensional array is an array in which the components are

arranged in a list form.

The general form of declaring a one-dimensional array is:

dataType arrayName[intExp];

where intExp is any expression that evaluates to a positive integer.

Page 7: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Example 9-1:

The statement

int num[5];

declares an array num of 5 components. Each component is of the type int. The components are num[0], num[1], num[2], num[3], and num[4].

Page 8: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Accessing Array ComponentsThe general form (syntax) of accessing an array component is:

arrayName[indexExp]

where indexExp, called index, is any expression whose value is a nonnegative integer.

Index value specifies the position of the component in the array. In C++, [] is an operator, called the array subscripting operator. In C++ array index starts at 0.

Page 9: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

int list[10];

Page 10: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

list[5] = 34;

Page 11: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

• If i is an int variable, the assignment statement

list[3] = 63;

is equivalent to the assignment statements

i = 3;

list[i] = 63;

• If i is 4, then the assignment statement

list[2*i-3] = 58;

stores 58 in list[5], because 2*i-3 evaluates to 5.

Page 12: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

list[3] = 10;list[6] = 35;list[5] = list[3]+ list[6];

Page 13: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Example 9-2You can also declare arrays as follows:             

const int arraySize = 10; 

int list[arraySize];

•When you declare an array, its size must be known.                 

int arraySize; //Line 1

 

cout<<"Enter the size of the array: ";//Line 2

cin>>arraySize; //Line 3

cout<<endl; //Line 4

 

int list[arraySize]; //Line 5; not allowed

Page 14: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Processing One-Dimensional Arrays Some of the basic operations performed on a one-dimensional array

are initialize, input data, output data stored in an array, find the largest and/or smallest element.

Each of these operations requires the ability to step through the elements of the array.

Stepping-through the elements of an array is easily accomplished by a loop.

Page 15: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Consider the declaration.

int list[100]; //list is an array of the size 100int i;

The following for loop steps-through each element of the array list starting at the first element of list.

for(i = 0; i < 100; i++) //Line 1 process list[i] //Line 2

If processing list requires inputting data into list, the statement in Line 2 takes the from of an input statement, such as the cin statement.

for(i = 0; i < 100; i++) //Line 1 cin>>list[i];

Page 16: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Example 9-3

double sale[10];

int index;

double largestSale, sum, average;

(a) Initializing an array:

for(index = 0; index < 10; index++)

sale[index] = 0.0;

(b) Reading data in an array:

for(index = 0; index < 10; index++)

cin>>sale[index];

(c) Printing an array:

for(index = 0; index < 10; index++)

cout<<sale[index]<<" ";

Page 17: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

(d) Finding the sum and average of an array:

sum = 0;

for(index = 0; index < 10; index ++)

sum = sum + sale[index];

average = sum / 10;

(e) Largest element in the array

maxIndex = 0;

for(index = 1; index < 10; index ++)

if(sale[maxIndex] < sale[index])

maxIndex = index;

largestSale = sale[maxIndex];

Page 18: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

maxIndex = 0; index = 1;

id mId sale[mId] sale[id] sale[mId]<sale[id]1 0 12.50 8.35 12.50 < 8.35 is false2 0 12.50 19.60 12.50 < 19.60 is true; mId = 23 2 19.60 25.00 19.60 < 25.00 is true; mId = 34 3 25.00 14.00 25.00 < 14.00 is false5 3 25.00 39.43 25.00 < 39.43 is true; mId = 56 5 39.43 35.90 39.43 < 35.90 is false7 5 39.43 98.23 39.43 < 98.23 is true; mId = 78 7 98.23 66.25 98.23 < 66.65 is false9 7 98.23 35.64 98.23 < 35.64 is false

In the above table id stands for index and mId stands for maxIndex

Page 19: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Example 9-4//Program to read five numbers, find their sum, and //print the numbers in reverse order.

#include <iostream>using namespace std;

int main(){ int item[5]; //declare an array item of five components

int sum;int counter;

cout<<"Enter five numbers."<<endl;

sum = 0;

Page 20: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

for(counter = 0; counter < 5; counter++){

cin>>item[counter];sum = sum + item[counter];

}

cout<<"The sum of the numbers is: "<<sum<<endl;cout<<"The numbers in reverse order are: ";

//print numbers in reverse orderfor(counter = 4; counter >= 0; counter--)

cout<<item[counter]<<" ";

cout<<endl;return 0;

}

Page 21: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Sample Run: The user input is in red.

Enter five numbers.

12 76 34 52 89

The sum of the numbers is: 263The numbers in reverse order are: 89 52 34 76 12

Page 22: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Array Index Out of Bounds

double num[10];

int i;

The component num[i] is valid, that is, i is a valid index, if i = 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9.

The index, say index, of an array is in bounds if index >=0 and index <= arraySize-1.

If either index < 0 or index > arraySize-1, then we say that the index is out of bounds.

In C++, there is no guard against indices that are out of bounds. That is, C++ does not check if the index value is with in range, that is, between 0 and arraySize-1.

Page 23: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

A loop such as the following can set the index out of bounds.

for(i = 0; i <= 10; i++)

list[i]=0;

Here we assume that list is an array of 10 components.

Page 24: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Array Initialization During Declaration Like any other simple variable, arrays can also be initialized while

they are being declared.

double sales[5] = {12.25, 32.50, 16.90, 23, 45.68};

sales[0] = 12.25, sales[1] = 32.50, sales[2] = 16.90, sales[3] = 23.00, and sales[4]=45.68.

When initializing arrays while declaring them, it is not necessary to specify the size of the array.

The size of the array is determined by the number of initial values in the braces.

double sales[] = {12.25, 32.50, 16.90, 23, 45.68};

Page 25: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Partial Initialization of Arrays During Declaration The statement

int list[10] = {0};

declares list to be an array of 10 components and initializes all components to zero.

The statement

int list[10] = {8, 5, 12};

declares list to be an array of 10 components, initializes list[0] to 8, list[1] to 5, list[2] to 12 and all other components are initialized to 0.

Page 26: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

The statement

int list[] = {5,6,3};

declares list to be an array of 3 components and initializes list[0] to 5, list[1] to 6, and list[2] to 3

The statement

int list[25]= {4,7};

declares list to be an array of 25 components. The first two components are initialized to 4 and 7, respectively and all other components are initialized to zero.

Page 27: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Some Restrictions on Array Processing Suppose x and y are two arrays of the same type and size, say 25.

Then the following statement is illegal:

y = x; // illegal

In order to copy one array into another array we must copy component-wise. This can be accomplished by a loop like the following.

for(j = 0; j < 25; j++)

y[j] = x[j];

Similarly comparison of arrays, reading data into an array and printing the contents of an array must be done component-wise.

cin>>x; //illegal

cout<<y; //illegal

Page 28: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

if(x <= y) //illegal

.

.

.

• C++ does not allows aggregate operations on array.

• An aggregate operation on an array is any operation that manipulates the entire array as a single unit.

Page 29: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Arrays as Parameters to Functions By Reference Only: In C++, arrays are passed by reference only.

Since arrays are passed by reference only, we do not use the symbol & when declaring an array as a formal parameter.

When declaring a one-dimensional array as a formal parameter the size of the array is usually omitted.

If we specify the size of the one-dimensional array when it is declared as a formal parameter, it is ignored by the compiler.

Page 30: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

void initialize(int list[5]){int count;for(count = 0; count < 5; count++)

list[count] = 0;}

The for loop inside the function executes 5 times, the above function will correctly initialize any int array of size 5 to zero.

If we add another formal parameter, say size in the function heading, use the value of size to control the for loop iterations, and pass the name of the actual array together with its size during call, then we can use the same function for any size array.

void initialize(int list[], int size){int count;for(count = 0; count < size; count++)

list[count] = 0;}

Page 31: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Even though an array is always passed by reference, we can still prevent the function from changing the actual parameter.

This is accomplished by using the reserved word const in the declaration of the formal parameter.

void example(int x[], const int y[],

int sizeX, int sizeY)

{

.

.

.

}

Page 32: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Example 9-5//Function to initialize an array to 0void initializeArray(int x[],int sizeX){

int counter;

for(counter = 0; counter < sizeX; counter++) x[counter] = 0;

}

//Function to read data and store in an arrayvoid fillArray(int x[],int sizeX){

int counter;for(counter = 0; counter < sizeX; counter++) cin>>x[counter];

}

Page 33: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

//Function to print the array

void printArray(int x[],int sizeX)

{

int counter;

for(counter = 0; counter < sizeX; counter++)

cout<<x[counter]<<" ";

}

Page 34: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

//Function to find and return the sum of an array

int sumArray(int x[],int sizeX)

{

int counter;

int sum = 0;

for(counter = 0; counter < sizeX; counter++)

sum = sum + x[counter];

return sum;

}

Page 35: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

// Function to find and return the index of the

// largest element of an array

int indexLargestElement(const int x[],int sizeX)

{

int counter; int maxIndex = 0; //Assume first element is the largest

for(counter = 1; counter < sizeX; counter++)

if(x[maxIndex] < x[counter])

maxIndex = counter;

return maxIndex;

}

Page 36: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

//Function to copy one array into another array

void copyArray(const int x[], int y[],

int length)

{

int counter;

for(counter = 0; counter < length; counter++)

y[counter] = x[counter];

}

Page 37: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Base Address of an Array The base address of an array is the address (that is, the memory

location) of the first array component.

If list is a one-dimensional array, then the base address of list is the address of the component list[0].

When we pass an array as a parameter, the base address of the actual array is passed to the formal parameter.

Function can not return a value of the type array.

Page 38: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Example 9-6//Arrays as parameters to functions

#include <iostream>

using namespace std;

const int arraySize = 10;

void initializeArray(int x[],int sizeX);void fillArray(int x[],int sizeX);void printArray(const int x[],int sizeX);int sumArray(const int x[],int sizeX);int indexLargestElement(const int x[],int sizeX);void copyArray(const int x[], int y[], int length);

Page 39: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

int main(){ int listA[arraySize] = {0}; //Line 1 int listB[arraySize]; //Line 2

cout<<"Line 1: listA elements: "; //Line 3 printArray(listA,arraySize); //Line 4 cout<<endl; //Line 5

initializeArray(listB,arraySize); //Line 6

cout<<"Line 7: ListB elements: "; //Line 7 printArray(listB,arraySize); //Line 8 cout<<endl<<endl; //Line 9

cout<<"Line 10: Enter "<<arraySize <<" integers: "; //Line 10 fillArray(listA, arraySize); //Line 11 cout<<endl; //Line 12

Page 40: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

cout<<"Line 13: After filling listA elements are:" <<endl; //Line 13 printArray(listA,arraySize); //Line 14 cout<<endl<<endl; //Line 15

cout<<"Line 16: Sum of the elements of listA is: " <<sumArray(listA,arraySize)<<endl<<endl;

//Line 16 cout<<"Line 17: Location of the largest element in listA is: " <<indexLargestElement(listA,arraySize) + 1 <<endl; //Line 17 cout<<"Line 18: Largest element in listA is: " <<listA[indexLargestElement(listA,arraySize)] <<endl<<endl; //Line 18

copyArray(listA, listB, arraySize); //Line 19 cout<<"Line 20: After copying the elements of " <<"listA into listB"<<endl <<" listB elements are: "; //Line 20

Page 41: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

printArray(listB,arraySize); //Line 21 cout<<endl; //Line 22

return 0;}

//Place the definition of the functions initializeArray, //fillArray, and so on here. Example 9-6 gives the definitions//of these functions.

Page 42: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Sample Run: In this sample run, the user input is in red.

Line 1: listA elements: 0 0 0 0 0 0 0 0 0 0Line 7: ListB elements: 0 0 0 0 0 0 0 0 0 0

Line 10: Enter 10 integers: 33 77 25 63 56 48 98 39 5 12

Line 13: After filling listA elements are:33 77 25 63 56 48 98 39 5 12

Line 16: Sum of the elements of listA is: 456

Line 17: Location of the largest element in listA is: 7Line 18: Largest element in listA is: 98

Line 20: After copying the elements of listA into listB listB elements are: 33 77 25 63 56 48 98 39 5 12

Page 43: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Integral Data Type and Array Indices

enum paintType{Green, Red, Blue, Brown, White,

Orange, Yellow};

double paintSale[7];

paintType paint;

for(paint = Green; paint <= Yellow;

paint = static_cast<paintType>(paint + 1))

paintSale[paint] = 0.0;

paintSale[Red] = paintSale[Red] + 75.69;

Page 44: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Some other ways to declare arrays

const int noOfStudents = 20;

int testscore[noOfStudents];

Other forms of declaring arrays are:

const int size = 50;

typedef double list[size];

list a;

list mylist;

This is equivalent to

double a[50];

double mylist[50];

Page 45: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

C Strings (Character Arrays) Character array: An array whose components are of the type char

is called a character array.

ch = '\0';

String: A string is a sequence of zero or more characters enclosed in double quote marks.

C stings are null terminated. That is, the last character in a string is the null character.

"John L. Johnson"

"Hello there."

Page 46: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

There is a difference between 'A' and "A". The first one is character A and the second is string A.

Since strings are null terminated, "A" represents two characters, 'A' and '\0'.

"Hello" represents six characters, 'H', 'e', 'l', 'l', 'o', and '\0'.

To store 'A' we need only one memory cell of the type char, while to store "A", we need two memory cells of the type char, one for 'A' and the other for '\0'.

To store the string "HELLO" in computer we need six memory cells of the type char.

Consider the statement.

char name[16];

Since 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.

Page 47: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

char name[16] = {'J', 'o', 'h', 'n', '\0'};

During char array variable declaration, C++ allows the string notation to be used in the initialization statement.

char name[16] = "John"; //Line A

The statement

char name[] = "John"; //Line B

declares a string variable name of length large enough, that is, 5 (here) and stores "John" in it.

There is a difference between the last two statements. Both statements stores "John" in name.

The size of name in the statement in Line A is 16 while its size in the statement in Line B is 5.

Page 48: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Most of the rules that apply to other arrays also apply to character arrays.

Consider the statement

char studentName[26];

studentName = "Lisa L. Johnson"; //Illegal

Page 49: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

To use these functions the program must include the header file cstring via the include statement.

#include <cstring>

Page 50: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

String Comparison• In C++, C-strings are compared character by character using the

collating sequence of the system.

Let us assume that 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".

Page 51: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Example 9-7

char studentName[21];

char myname[16];

char yourname[16];

Statement Effect

a. strcpy(myname,"John Robinson"); myname=John Robinson

b. strlen("John Robinson"); Returns 13, the length

of the stringc. int len;

len = strlen ("Sunny Day"); Stores 9 into len

d. strcpy(yourname,"Lisa Miller"); yourname = Lisa Miller

strcpy(studentName,yourname); studentName = Lisa Miller

e. strcmp("Bill", "Lisa"); Returns a value < 0

f. strcpy(yourname, "Kathy Brown"); yourname = Kathy Brown

strcpy(myname, "Mark G. Clark"); myname = Mark G. Clark

strcmp(myname,yourname); Return a value > 0

Page 52: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Reading and Writing Strings

char name[31];

String Input Since aggregate operations are allowed for string input, the statement

cin>>name;

will store the next input string into name.

Strings that contain blanks cannot be read using the extraction operator >>.

Page 53: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

To read strings with blanks, the general form (syntax) of get function together with an input stream variable, such as cin is:

cin.get(str,m+1);

This statement stores the next m characters or until the newline character '\n' is found into str. The newline character is not stored in str.

If the input string has fewer than m characters, then the reading stops at the newline character.

Page 54: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Consider the following statements:

char str[31];cin.get(str,31);

If the input is

William T. Johnson

then "William T. Johnson" will be stored in str and

If the input is

Hello there. My name is Mickey Mouse.

then the string

"Hello there. My name is Mickey"

is stored in str.

Page 55: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

char str1[26];

char str2[26];

char discard;

Input is, say

Summer is warm.

Winter will be cold.

The following statements store line 1 in str1 and line 2 in str2.

cin.get(str1,26);

cin.get(discard);

cin.get(str2,26);

Page 56: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

String OutputThe statement

cout<<name;

will output the content of name on the screen.

The insertion operator << continues to write the contents of name until it finds the null character.

If name does not contain the null character, then we will see strange output since << continues to output data from memories adjacent to name until '\0' is found.

Page 57: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Specifying Input/Output Files at the Execution Time

ifstream infile;ofstream outfile;

char fileName[51];

cout<<"Enter the input file name: ";cin>>fileName;infile.open(fileName); //open the input file...

cout<<"Enter the output file name: ";cin>>fileName;outfile.open(fileName); /open the output file

Page 58: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

The string type and Input/Output Files

Values (that is, strings) of the type string are not null terminated. Variables of type string can also be used to read and store the

names of input/output files. The argument to the function open must be a null terminated string,

that is a C string. if we use a variable of the type string to read the name of an

input/output file and then use this variable to open a file, the value of the variable must (first) be converted to a C-string (that is, a null-terminated string).

Page 59: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

The header file string contains the function c_str, which converts a value of the type string to a null-terminated character array (that is, C-string).

The syntax to use the function c_str is

strVar.c_str()

where strVar is a variable of the type string.

Page 60: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

ifstream infile;

string fileName;

cout<<"Enter the input file name: ";

cin>>fileName;

infile.open(fileName.c_str()); //open the input file

Page 61: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Parallel ArraysTwo (or more) Arrays are called parallel if their corresponding components hold related information.

int studentId[50];

char courseGrade[50];

Page 62: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

PROGRAMMING EXAMPLE: CODE DETECTION

When a message is transmitted in secret code over a transmission channel, it is usually transmitted as a sequence of bits, that is, 0s and 1s.

Due to noise in the transmission channel, the transmitted message may become corrupted.

The message received at the destination is not the same as the message transmitted; some of the bits may have been changed.

There are several techniques to check the validity of the transmitted message at the destination.

One technique is to transmit the same message twice. At the destination, both copies of the message are compared bit by bit.

If the corresponding bits are the same, the message received is error-free.

Page 63: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

We write a program to check if the message received at the destination is error free.

For simplicity, we assume that the secret code representing the message is a sequence of digits (0 to 9) and the maximum length of the message is 250 digits.

Also, the first number in the message is the length of the message.

If the secret code is

7 9 2 7 8 3 5 6

then the message is 7 digits long. Also, the message is transmitted twice.

The above message is transmitted as

7 9 2 7 8 3 5 6 7 9 2 7 8 3 5 6

Page 64: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Input: A file containing the secret code and its copy.

Output: The secret code, its copy, and a message if the received code is error free in the following form:

Code Digit Code Digit Copy

9 9

2 2

7 7

8 8

3 3

5 5

6 6

Message transmitted OK.

Page 65: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Problem Analysis and Algorithm Design Because we have to compare the corresponding digits of the secret

code and its copy, you first read the secret code and store it in an array.

Then you read the first digit of the copy and compare it with the first digit of the secret code, and so on.

If any corresponding digits are not the same, you indicate this fact by printing a message next to the digits.

Because the maximum length of the message is 250, you use an array of 250 components.

The first number in the secret code, and in the copy of the secret code, indicates the length of the code.

Page 66: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

1. Open the input and output files.

2. If the input file does not exist, exit the program.

3. Read the length of the secret code.

4. If the length of the secret code is greater than 250, terminate the program because the maximum length of the code in this program is 250.

5. Read and store the secret code into an array.

6. Read the length of the copy.

7. If the length of the secret code and its copy are the same, compare the codes; otherwise, print an error message.

• To simplify the function main, we will write a function, readCode, to read the secret code and another function, compareCode, to compare the codes.

Page 67: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

readCode:

This function first reads the length of the secret code. If the length of the secret code is greater than 250, a Boolean variable lengthCodeOk, which is a reference parameter, is set to false and the function terminates. The value of lengthCodeOk is passed to the calling function to indicate whether the secret code was read successfully. If the length of the code is less than 250, the readCode function reads and stores the secret code into an array.

Page 68: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

void readCode(ifstream& infile, int list[], int& length, bool& lenCodeOk)

{ int count;

lenCodeOk = true;

infile>>length; //get the length of the secret code if(length > maxCodeSize) {

lenCodeOk = false; return;

}

for(count = 0; count < length; count++) //get the secret code

infile>>list[count];}

Page 69: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

compareCode a. Declare variables.b. Set a bool variable codeOk to true.c. Read the length of the copy of the secret code.d. If the length of the secret code and its copy are not the same,

output an appropriate error message and terminate the function.e. For each digit in the input file

e.1. Read the next digit of the copy of the secret code.e.2. Output the corresponding digits from the secret code and its

copy.e.3. if the corresponding digits are not the same, output an error

message and set the flag codeOk to false.f. If the bool variable codeOk is true

output a message indicating that the secret code transmitted OK else output an error message.

Page 70: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

void compareCode(ifstream& infile, ofstream& outfile, int list[], int length)

{//Step a

int length2; int digit; bool codeOk; int count;

codeOk = true; //Step b

infile>>length2; //Step c

if(length != length2) //Step d

{ cout<<"The original code and its copy are not of" <<" the same length."<<endl; return; }

Page 71: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

outfile<<"Code Digit Code Digit Copy"<<endl;

for(count = 0; count < length; count++) //Step e {

infile>>digit; //Step e.1outfile<<setw(7)<<list[count]<<setw(20)

<<digit; //Step e.2if(digit != list[count]) //Step e.3{

outfile<<" code digit not the same"<<endl;

codeOk = false; //Step e.3}else

outfile<<endl; }

if(codeOk) //Step foutfile<<"Message transmitted OK."<<endl;

elseoutfile<<"Error in transmission. Retransmit!!"<<endl;

}

Page 72: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Main Algorithm1. Declare Variables.

2. Open the files.

3. Call the function readCode to read the secret code.

4. If (length of the secret code <= 250)

Call the function compareCode to compare the codes.

else

Output an appropriate error message.

Page 73: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

//Program: Check Code

#include <iostream>

#include <fstream>

#include <iomanip>

using namespace std;

const int maxCodeSize = 250;

void readCode(ifstream& infile, int list[],

int& length, bool& lenCodeOk);

void compareCode(ifstream& infile,

ofstream& outfile, int list[], int length);

Page 74: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

int main()

{

//Step 1

int codeArray[maxCodeSize]; //array to store

//the secret code

int codeLength; //variable to store the

//length of the secret code

bool lengthCodeOk; //variable to indicate if

//the length of the secret code

//is less than or equal to 250

ifstream incode; //input file stream variable

ofstream outcode; //output file stream variable

char inputfile[25]; //variable to store the name

//of the input file

char outputfile[25]; //variable to store the name

//of the output file

Page 75: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

cout<<"Enter the input file name: ";

cin>>inputfile;

cout<<endl;

//Step 2

incode.open(inputfile);

if(!incode)

{

cout<<"Cannot open the input file."<<endl;

return 1;

}

cout<<"Enter the output file name: ";

cin>>outputfile;

cout<<endl;

outcode.open(outputfile);

Page 76: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

readCode(incode, codeArray, codeLength, lengthCodeOk);//Step 3

if(lengthCodeOk) //Step 4

compareCode(incode, outcode, codeArray, codeLength);

else cout<<"Length of the secret code must be <= "

<<maxCodeSize<<<<endl; //Step 5

incode.close();

outcode.close();

return 0;

}

Page 77: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

//Place the definitions of the functions

//readCode and compareCode here

Page 78: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

PROGRAMMING EXAMPLE: TEXT PROCESSING(Line and letter count) Let us now write a program that reads a given text, outputs the text as is, and also prints the number of lines and the number of times each letter appears in the text. An uppercase letter and a lowercase letter are treated as being the same; that is, they are tallied together.

Since there are 26 letters, we will use an array of 26 components to do the letter count. We also need a variable to store the line count.

The text is stored in a file, say textin.txt (and is on floppy drive, say a). The output will be stored in a file, say textout.out.

Input: A file containing the text to be processed.

Output: A file containing the text, number of lines, and the number of times a letter appears in the text.

Page 79: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Problem Analysis and Algorithm Design Based on the desired output, it is clear that we must output the text as

is. That is, if the text contains any whitespace characters, they must be output as well.

We must count the number of lines in the text. Therefore, we must know where the line ends, which means that we must trap the newline character.

This requirement suggests that we cannot use the extraction operator to process the input file. Because we also need to perform the letter count, we use the get function to read the text.

Page 80: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Variables (Function main)int lineCount;

int letterCount[26];

char ch;

ifstream infile; //input file stream variable

ofstream outfile; //output file stream variable

Page 81: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

1. Declare variables.

2. Open the input and output files.

3. Initialize the variables.

4. While there in more data in the input file

4.1 For each character in a line

4.1.1 Read and write the character.

4.1.2 Increment the appropriate letter count.

4.2 Increment the line count.

5. Output line count and letter counts.

6. Close files.

Page 82: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Function Initialize. Function copyText. Function characterCount. Function writeTotal.

Page 83: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Function initialize:

void initialize(int& lc, int list[])

{

int j;

lc = 0;

for(j = 0; j < 26; j++)

list[j] = 0;

}

Page 84: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Function copyText This function reads a line and outputs the line. Whenever a nonblank

character is found it calls the function characterCount to update the letter count.

This function has four parameters, input file stream variable, output file stream variable, a char variable, and the array to update the letter count.

Page 85: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

void copyText(ifstream& intext, ofstream& outtext,

char& ch, int list[])

{

while(ch != '\n') //Process the entire line

{

outtext<<ch; //Output the character

characterCount(ch,list); //Call function character count

intext.get(ch); //Read the next character

}

outtext<<ch; //Output the newline character

}

Page 86: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Function characterCount

a. Convert the letter to upper case.

b. Find the index of array corresponding to this letter.

c. If the index is valid, increment appropriate count.

void characterCount(char ch, int list[])

{

int index;

ch = toupper(ch); //Step a

index = static_cast<int>(ch) – 65; //Step b

if(0 <= index && index < 26) //Step c

list[index]++;

}

Page 87: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Function writeTotal

void writeTotal(ofstream& outtext, int lc,

int list[])

{

int index;

outtext<<"The number of lines = "<<lc<<endl;

for(index = 0; index < 26; index++)

outtext<<static_cast<char>(index+65)

<<" count = "

<<list[index]<<endl;

}

Page 88: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

Main Algorithm1. Declare variables. 2. Open the input and output files.3. If the input file does not exist, exit the program. 4. Open the output file.5. Initialize variables, such as lineCount and the array

letterCount.6. Read the first character.7. while (not end of input file)

7.1 Process the next line. Call the function copyText;7.2 Increment the line count. (Increment the variable lineCount.)

7.3 Read the next character.8. Output the line count and letter counts. Call function

writeTotal.9. Close Files.

Page 89: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

//Program: Line and letter count#include <iostream>#include <fstream>#include <cctype>

using namespace std;

void initialize(int& lc, int list[]);void copyText(ifstream& intext, ofstream& outtext,

char& ch, int list[]);void characterCount(char ch, int list[]);void writeTotal(ofstream& outtext, int lc,

int list[]);

int main(){

//Step 1; Declare variablesint lineCount;int letterCount[26];char ch;ifstream infile; ofstream outfile;

Page 90: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

infile.open("a:textin.txt"); //Step 2

if(!infile) //Step 3{ cout<<"Cannot open input file."<<endl; return 1;

}

outfile.open("a:textout.out"); //Step 4

initialize(lineCount, letterCount); //Step 5

infile.get(ch); //Step 6while(infile) //Step 7{

copyText(infile,outfile,ch,letterCount);//Step 7.1

lineCount++; //Step 7.2infile.get(ch); //Step 7.3

}

Page 91: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

writeTotal(outfile,lineCount,letterCount);//Step 8

infile.close(); //Step 9outfile.close(); //Step 9return 0;

}

Page 92: CHAPTER 9 ARRAYS AND STRINGS. In this chapter, you will: Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning.

//Place the definitions of the functions

//initialize, copyText, characterCount, and

//writeTotal here