+ All Categories
Home > Documents > 10-ArraysAndStrings[1]

10-ArraysAndStrings[1]

Date post: 29-May-2018
Category:
Upload: mia-357
View: 219 times
Download: 0 times
Share this document with a friend
47
  © Christian Jacob  Chapter Overview  Chapter 10 Arrays and Strings  10.1 Arrays 10.2 One-Dimensional Arrays  10. 2.1 Acc ess ing Arr ay Elements 10.2.2 Representation of Ar rays in Memory 10.2.3 Example: Finding the Maximum 10.2.4 No Array-to-Array Assi gnments 10.2.5 No Bounds Checking  10.3 Strings  10.3.1 Rea ding a Stri ng fr om the Keyboard 10.3.2 Some C++ Libr ary F unc tions for Str ings 10.3.3 Usi ng the Null Terminator
Transcript
Page 1: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 1/47

Page 2: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 2/47

 

 © Christian Jacob

  Chapter Overview

 

10.4 Two-Dimensional Arrays

10.5 Multidimensional Arrays

10.6 Array Initialization

 

10.6.1 Character Array Initialization

10.6.2 Multi-Dimensional Array Initialization10.6.3 Unsized Array Initializations

 

10.7 Arrays of Strings

10.8 An Example Using String Arrays

 

10.8.1 Entering Information

10.8.2 Displaying Database Contents

10.8.3 Menu For User´s Selection

10.8.4 Main Function

10.8.5 Putting It All Together

 

10.9 References

Page 3: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 3/47

 

Page 3

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Prev Next Last

 

10.1 Arrays

 

An array

 

is a collection

 

of variables of the same type

 

that are referred to by a common name

 

.

Arrays offer a convenient means of grouping together severalrelated variables, in one dimension or more dimensions:

• product part numbers:

int part_numbers[] = {123, 326, 178, 1209};

 

• student scores:

int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};

 

• characters:char alphabet[5] = {’A’, ’B’, ’C’, ’D’, ’E’};

Page 4: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 4/47

 

Page 4

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Prev Next Last

 

• names:

char names[][40] ={“Peter”, “Mary”, “Lisa”, “John”, "George-Simon"};

 

• 3D coordinates:

vector coordinates[4][3] ={{0, 0, 0},{1, 0, 1},{1, 0, 5}

{4, 7, 9}};

Page 5: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 5/47

 

Page 5

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC One-Dimensional Arrays Prev Next Last

 

10.2 One-Dimensional Arrays

 

A one-dimensional array is a list of related variables. The generalform of a one-dimensional array declaration is:

 

type

 

variable_name

 

[

 

 size

 

]•

 

type

 

: base type of the array,determines the data type of each element inthe array

 

 size

 

: how many elements the array will hold

 

variable_name

 

: the name of the array

 

Examples

 

:

 

int sample[10];

 

float

 

float_numbers[100];

char last_name[40];

Page 6: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 6/47

 

Page 6

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC One-Dimensional Arrays Prev Next Last

 

10.2.1 Accessing Array Elements

 

An individual element within an array is accessed by use of an index

 

.

An index describes the position of an element within an array.

 

Note

 

: In C++ the first element has the index zero

 

!

Page 7: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 7/47

 

Page 7

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC One-Dimensional Arrays Prev Next Last

 

Example

 

: Load the array sample

 

with the numbers 0

 

2

 

through 9

 

2

 

#include <iostream.h>

int main()

{int sample[10]; // reserves for 10 integers

 

int t;

 

// initialize the array

 

for(t=0; t<10; ++t) sample[t] = t*t;

 

// display the array

 

for(t=0; t<10; ++t)cout << sample[t] << ‘ ‘;

return(0);}

Page 8: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 8/47

 

Page 8

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC One-Dimensional Arrays Prev Next Last

 

10.2.2 Representation of Arrays in Memory

 

In C++, any array is mapped to a contiguous memory location.

All memory elements reside next to each other.

The lowest address corresponds to the first element, and the highestaddress to the last element.

Page 9: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 9/47

 

Page 9

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC One-Dimensional Arrays Prev Next Last

 

Example

 

:

 

int a[8];

int j;

for(j=0; j<8; j++) a[j] = 7-j;

 

Then the memory representation of array a

 

looks like this:

a[0]

7

a[1]

6

a[2]

5

a[3]

4

a[4]

3

a[5]

2

a[6]

1

a[7]

0

Page 10: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 10/47

 

Page 10

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC One-Dimensional Arrays Prev Next Last

 

10.2.3 Example: Finding the Maximum

 

#include <iostream.h>

int main()

{

int i, max = 0;int list[100];

 

// initialize the array with random values

 

for(i=0; i<100; i++) list[i] = rand();

 

// find maximum value

 

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

if(max < list[i]) max = list[i];

cout << “Maximum value: “ << max;

return(0);

}

Page 11: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 11/47

 

Page 11

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC One-Dimensional Arrays Prev Next Last

 

10.2.4 No Array-to-Array Assignments

 

You cannot assign one array to another in C++.

The following is illegal:

 

int a[10], b[10];

// do something

 

// assign all elements of array b to array a

 

a = b; // error -- illegal

 

Instead, you have to do the assignments for each element:

 

int i;

 

// assign all elements of array b to array a

 

for(i=0; i<10; i++) a[i] = b[i];

Page 12: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 12/47

 

Page 12

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC One-Dimensional Arrays Prev Next Last

 

10.2.5 No Bounds Checking

 

C++ performs no bounds checking on arrays.

Nothing will stop you from overrunning the end of an array:

 

©

 

You will assign values to some other variables´ data!!!

 

©

 

You might even write into a piece of the program code!!!

Page 13: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 13/47

 

Page 13

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC One-Dimensional Arrays Prev Next Last

 

For example, you can compile and run the following program, even

though the array crash

 

is being overrun:

 

// An incorrect program. Do not execute!

int main()

{

int crash[10], i;

for(i=0; i<100

 

; i++) crash[i] = i;

return(1);

}

Page 14: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 14/47

 

Page 14

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

10.3 Strings

 

The most common use for one-dimensional arrays is to store stringsof characters

 

.

In C++, a string

 

is defined as a character array terminated by a nullsymbol ( ‘\0’

 

).

To declare an array str

 

that could hold a 10

 

-character string, onewould write:

 

char str[11];

 

Specifying the size as 11

 

makes room for the null at the end of thestring.

‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’

Page 15: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 15/47

 

Page 15

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

Some examples of string constants

 

in C++ are:

 

"hello there"

"I like C++."

"#$%§@@+*"

"\"""\"\""

"\\"

""

 

The null string

 

, ““, only contains the null terminator and representsthe empty string.

Page 16: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 16/47

 

Page 16

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

10.3.1 Reading a String from the Keyboard

 

How to read a string entered from the keyboard?

Make an array, that will receive the string, the target of a cin

 

stream.

The following program reads (part of) a string entered by the user:

 

#include <stdio.h>

int main()

{char str[80];

cout << “Enter a string: “;

cin >> str; // read string from keyboard

 

cout << “Here is your string: “;

cout << str;

return(0);}

Page 17: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 17/47

 

Page 17

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

Problem: Entering the string “

 

This is a test

 

”, the above program only

returns “

 

This

 

”, not the entire sentence.

Reason: The C++ input/output system stops reading a string whenthe first whitespace

 

character is encountered.

Solution: Use another C++ library function, gets()

 

.

 

#include <iostream.h>

#include <

 

cstdio.h

 

>

int main(){

char str[80]; // long enough for user input?

 

cout << “Enter a string: “;

gets(str); // read a string from the keyboard

 

cout << “Here is your string: “;

cout << str << endl;

return(0);}

Page 18: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 18/47

 

Page 18

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

10.3.2 Some C++ Library Functions for Strings

 

C++ supports a range of string-manipulation functions.

The most common are:

 

strcpy()

 

: copy characters from one string to another•

 

strcat()

 

: concatenation of strings

 

strlen()

 

: length of a string

 

strcmp()

 

: comparison of strings

Page 19: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 19/47

 

Page 19

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

strcpy(

 

to_string

 

, from_string

 

) — String Copy:

#include <iostream.h>

#include <

 

cstring.h

 

>

int main()

{

char a[10];

strcpy(a, “hello”);

cout << a;

return(0);

}

a[0]

h

a[1]

e

a[2]

l

a[3]

l

a[4]

o

a[5]

\0

a[6]

?

a[7]

?

a[8]

?

a[9]

?

Page 20: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 20/47

 

Page 20

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

strlen(

 

 string

 

) — String Length

 

strlen(str)

 

returns the length of the string pointed to by str

 

, i.e.,the number of characters excluding

 

the null terminator.

 

#include <iostream.h>

#include <cstdio.h>#include <cstring.h>

int main()

{char str[80];

cout << “Enter a string: “;

gets(str);

cout << “Length is: “ << strlen(str);

return(0);}

Page 21: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 21/47

 

Page 21

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

strcat(

 

 string_1

 

, string_2

 

) — Concatenation of Strings

 

The strcat() function appends s2

 

to the end of s1

 

. String s2

 

isunchanged.

 

// includes ...

int main(){

char s1[21], s2[11];

strcpy(s1, “hello”);strcpy(s2, “ there”);

strcat(s1, s2);

cout << s1 << endl;cout << s2 << endl;

return(0);

}

Page 22: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 22/47

 

Page 22

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

Output:

 

hello

 

there

there

Ch 0 A d S i

Page 23: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 23/47

 

Page 23

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

Note:

• The first string array has to be large enough

 

to hold both strings:

• To be on the safe side:strlen(s1concats2) >= strlen(s1) + strlen(s2)

0

h

1

e

2

l

3

l

4

o

5

\0

6

?

7

?

8

?

9

?

0

‘ ‘

1

t

2

h

3

e

4

r

5

e

6

\0

7

?

8

?

9

?

10

?

11

?

12

?

13

?

14

?

15

?

16

?

17

?

18

?

19

?

10

?

20

?s1:

s2:

0

h

1

e

2

l

3

l

4

o

5

‘ ‘

6

t

7

h

8

e

9

r

10

e

11

\0

12

?

13

?

14

?

15

?

16

?

17

?

18

?

19

?

20

?strcat(s1,s2):

Ch t 10 A d St i

Page 24: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 24/47

 

Page 24

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

strcmp(

 

 string_1

 

, string_2

 

) — Comparison of Strings

 

The strcmp(str_1, str_2)

 

function compares two strings andreturns the following result:

• str_1 == str_2 : 0

• str_1 > str_2 : positive number

• str_1 < str_2 : negative number

The strings are compared lexicographically 

 

(i.e., according todictionary order):

a < aa < aaa < … < b < ba < bb < … < bz < baa < … < abca < abd < ...

P 25 Chapter 10: Arrays and Strings ©

Page 25: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 25/47

 

Page 25

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

Lexicographical order:

 

Given: Two words over an alphabet , and an ordering

relation “<“ on the elements of the alphabet.

 

a b Σ+

∈, Σ

a b< : ⇔ w Σ*

∈( ) x y Σ∈,( ) v1 v2, Σ*

∈( )∃( )∃∃

a wxv1

=( ) b wxv2

=( ) x y<( )∧ ∧( )

P 26 Chapter 10: Arrays and Strings © Ch i ti J b

Page 26: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 26/47

 

Page 26

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

// Comparing strings

 

#include <iostream.h>#include <cstring.h>

#include <cstdio.h>

int main(){

char str[80];

cout << “Enter password: “;gets(str);

if(strcmp(str, “password”)) {

// strings differcout << “Invalid password.\n”;}

else cout << “Logged on.\n”;

return(0);

}

Page 27 Chapter 10: Arrays and Strings © Christian Jacob

Page 27: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 27/47

 

Page 27

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Strings Prev Next Last

 

10.3.3 Using the Null Terminator

 

Operations on strings can be simplified using the fact that all stringsare null-terminated.

 

// Convert a string to uppercase

// ... includes ...

 

int main()

{

char str[80];

int i;

strcpy(str, “this is a test”);

for(i=0; str[i]; i++)str[i] = toupper(str[i]);

cout << str; return(0); }

Page 28 Chapter 10: Arrays and Strings © Christian Jacob

Page 28: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 28/47

 

Page 28

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Two-Dimensional Arrays Prev Next Last

 

10.4 Two-Dimensional Arrays

 

A two-dimensional array is a list of one-dimensional arrays.

To declare a two-dimensional integer array two_dim

 

of size 10,20 wewould write:

 

int matrix[

 

3

 

][

 

4

 

];

 

This corresponds to a table with 3 rows and 4 columns (for example).

 

1 2 3 4

5 6 7 8

9 10 11 12

 

0 1 2 3

0

1

2

 Left Index

Right Index

two_dim[1][2]

Page 29 Chapter 10: Arrays and Strings © Christian Jacob

Page 29: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 29/47

 

Page 29

 

Chapter 10: Arrays and Strings

 

 © Christian Jacob

First Back TOC Two-Dimensional Arrays Prev Next Last

 

We can generate the array above by using this program:

 

#include <iostream.h>

int main()

{

int row=3, col=4;

int matrix[row][col];

for(row=0; row < 3; ++row) {

for(col=0; col < 4; ++col) {

matrix[row][col] = (row*4)+ col +1;

cout << matrix[row][col] << ‘ ‘;

}cout << ‘\n’;

}

return(0);}

Page 30 Chapter 10: Arrays and Strings  © Christian Jacob

Page 30: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 30/47

 

g

 

p y g

 

First Back TOC Two-Dimensional Arrays Prev Next Last

 

Memory Allocation for Two-Dimensional Arrays

 

Storage for all array elements is determined at compile time.

The memory used to hold an array is required the entire time thatthe array is in existence.

The following formula determines the number of bytes of memorythat will be allocated:

bytes = rows * columns * number_of_bytes_in_type

For example, an integer array (with two-byte integers) withdimensions 100,100 would require 100 * 100 * 2 = 20,000 bytes.

Page 31 Chapter 10: Arrays and Strings  © Christian Jacob

Page 31: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 31/47

  

p y g

 

First Back TOC Multidimensional Arrays Prev Next Last

 

10.5 Multidimensional Arrays

 

C++ allows arrays with more than two dimensions.

The general form of an N

 

-dimensional array declaration is:

 

type

 

array_name

 

[

 

size_1

 

] [

 

size_2

 

] … [

 

size_

 

 

];

For example, the following declaration creates a 4 x 10 x 20 characterarray, or a matrix of strings:

 

char string_matrix[4][10][20];

 

This requires 4 * 10 * 20 = 800 bytes.

If we scale the matrix by 10, i.e. to a 40 x 100 x 20 array, then 80,000bytes are needed.

Page 32 Chapter 10: Arrays and Strings  © Christian Jacob

Page 32: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 32/47

   

First Back TOC Array Initialization Prev Next Last

 

10.6 Array Initialization

 

The general form of array initialization is similar to that of othervariables:

 

type

 

array-name

 

[

 

 size

 

] = { list-of-values };

The list-of-values

 

has to be a comma-separated list of constants

 

thatare type-compatible with the base type of the array.

In the following example, a 10-element float array is initialized withthe numbers 1.0 through 10.0:

 

float i[10] = {1.,2.,3.,4.,5.,6,7,8,9,10};

 

Therefore, i[0]

 

will have the value 1.0

 

, and i[9]

 

will have thevalue 10.0

 

.

Page 33 Chapter 10: Arrays and Strings  © Christian Jacob

Page 33: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 33/47

   

First Back TOC Array Initialization Prev Next Last

 

10.6.1 Character Array Initialization

 

Character arrays that will hold strings allow a shorthand initializationthat takes this form:

char array-name

 

[

 

 size

 

] = “

 

 string

 

”;

For example, the following code fragment initializes str

 

to thephrase “hello”:

 

char str[6] = “hello”;

 

This is the same as writing

 

char str[6] =

{‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

 

Remember that one has to make sure to make the array long enoughto include the null terminator.

Page 34 Chapter 10: Arrays and Strings  © Christian Jacob

Page 34: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 34/47

   

First Back TOC Array Initialization Prev Next Last

 

10.6.2 Multi-Dimensional Array Initialization

 

Multi-dimensional arrays are initialized the same way as one-dimensional arrays.

For example, the following code fragment initializes an array

squares

 

with the numbers 1 through 10 and their squares:

 

int squares[9][2] =

{ 1, 1,

2, 4,

3, 9,

4, 16,

5, 25,

6, 36,

7, 49,

8, 64,

9, 81 };

Page 35 Chapter 10: Arrays and Strings  © Christian Jacob

Page 35: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 35/47

   

First Back TOC Array Initialization Prev Next Last

 

For better readability, especially for multi-dimensional arrays, one

can use subaggregate grouping

 

by adding braces accordingly.

The same declaration as above can also be written as:

 

int squares[10][2] =

{{1, 1},

{2, 4},

{3, 9},

{4, 16},{5, 25},

{6, 36},

{7, 49},

{8, 64},{9, 81},

{10, 100}

};

Page 36 Chapter 10: Arrays and Strings  © Christian Jacob

Page 36: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 36/47

   

First Back TOC Array Initialization Prev Next Last

 

The following program uses the squares

 

array to find the root of a

number entered by the user.

 

#include <iostream.h>

 

// declaration of squares array goes here

 

int main()

{

int i, j;

cout << “Enter a number 1<=i<=100: “;

cin >> i;

 

// look up i

 

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

if(squares[j][1] == i) {cout << "Root: " << squares[j][0];

return(0);}

cout << "No integer root."; return(0);}

Page 37 Chapter 10: Arrays and Strings  © Christian Jacob

Page 37: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 37/47

   

First Back TOC Array Initialization Prev Next Last

 

10.6.3 Unsized Array Initializations

 

It is possible to let C++ automatically dimension the arrays throughthe use of unsized arrays

 

.

 

char error_1[] = “Divide by 0\n”;

char error_2[] = “End-of-File\n”;char error_3[] = “Access Denied\n”;

 

C++ will automatically create arrays large enough to hold all theinitializers present.

For a multi-dimensional array, all but the leftmost

 

dimension have tobe specified. So we can write:

 

char errors[][20] = {“Divide by 0\n”,

“End-of-File\n”,

“Access Denied\n” };

Page 38 Chapter 10: Arrays and Strings  © Christian Jacob

Page 38: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 38/47

   

First Back TOC Arrays of Strings Prev Next Last

 

10.7 Arrays of Strings

 

An array of strings is a special form of a two-dimensional array.

• The size of the left

 

index determines the number of strings.

• The size of the right

 

index specifies the maximum length

 

of each

string.

For example, the following declares an array of 30 strings, eachhaving a maximum length of 80 characters (with one extra characterfor the null terminator):

 

char string_array[30][81];

Page 39 Chapter 10: Arrays and Strings  © Christian Jacob

Page 39: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 39/47

   

First Back TOC Arrays of Strings Prev Next Last

 

For accessing an individual string, one simply specifies only the left

index:

 

firstString = string_array[0];

sixthString = string_array[5];

 

The following example calls the gets()

 

function with the third stringin the array:

 

gets(string_array[2]);

Page 40 Chapter 10: Arrays and Strings  © Christian Jacob

Page 40: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 40/47

   

First Back TOC Arrays of Strings Prev Next Last

 

This program accepts lines of text entered at the keyboard and

redisplays them after a blank line is entered.

 

// includes go here

 

int main()

{

int t, i;

char text[100][80];

for(t=0; t<100; t++) {

cout << t << “: “;gets(text[t]);

if(!text[t][0]) break; // quit on blank line

 

}

for(i=0; i<t; i++) // redisplay the strings

 

cout << text[i] << ‘\n’;

return(0);}

Page 41 Chapter 10: Arrays and Strings  © Christian Jacob

Page 41: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 41/47

   

First Back TOC An Example Using String Arrays Prev Next Last

 

10.8 An Example Using String Arrays

 

Arrays of strings are commonly used for handling tables ofinformation.

One such application would be an employee database that stores

• the name

• telephone number

• hours worked per pay period, and

• hourly wage.

These data we could store in arrays:

 

char name[20][80]; // employee namesint phone[20]; // phone numbers

float hours[20]; // hours worked

float wage[20]; // wage

Page 42 Chapter 10: Arrays and Strings  © Christian Jacob

Page 42: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 42/47

   

First Back TOC An Example Using String Arrays Prev Next Last

 

10.8.1 Entering Information

 

void enter()

{

int i;

for(i=0; i<20; i++) {

cout << “Last name: “;

cin >> name[i];

cout << “Phone number: “;

cin >> phone[i];

cout << “Hours worked: “;

cin >> hours[i];

cout << “Wage: “;

cin >> wage[i];}

}

Page 43 Chapter 10: Arrays and Strings  © Christian Jacob

Page 43: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 43/47

   

First Back TOC An Example Using String Arrays Prev Next Last

 

10.8.2 Displaying Database Contents

 

void report()

{

int i;

for(i=0; i < 20; i++) {

cout << "Name: " << name[i] << " / "

<< "phone: " << phone[i] << ‘\n’;

cout << “Pay for the week: “;

cout << wage[i] * hours[i];cout << ‘\n’;

}

}

Page 44 Chapter 10: Arrays and Strings  © Christian Jacob

Page 44: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 44/47

   

First Back TOC An Example Using String Arrays Prev Next Last

 

10.8.3 Menu For User´s Selection

 

int menu()

{

int choice;

cout << “0. Quit\n”;

cout << “1. Enter information\n”;

cout << “2. Report information\n”;

cout << “\n”;

cout << “Choose one: “;cin >> choice;

return choice;

}

Page 45 Chapter 10: Arrays and Strings  © Christian Jacob

Page 45: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 45/47

   

First Back TOC An Example Using String Arrays Prev Next Last

 

10.8.4 Main Function

 

int main()

{

int choice;

do {

choice = menu(); // get selection

switch(choice) {

case 0: break;

case 1: enter(); break;case 2: report(); break;

default: cout << “Try again.\n\n”;

}

} while( choice != 0);

return(0);

}

Page 46 Chapter 10: Arrays and Strings  © Christian Jacob

Page 46: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 46/47

   

First Back TOC An Example Using String Arrays Prev Next Last

 

10.8.5 Putting It All Together

 

#include <iostream.h>

// array declarations

int menu();

void enter();

void report();

int main() { ... }

int menu() { ... }

void enter() { ... }

void report() { ... }

Page 47 Chapter 10: Arrays and Strings  © Christian Jacob

Page 47: 10-ArraysAndStrings[1]

8/8/2019 10-ArraysAndStrings[1]

http://slidepdf.com/reader/full/10-arraysandstrings1 47/47

   

First Back TOC References Prev Next Last

 

10.9 References

 

• Schildt, H., C++ from the Ground Up

 

, Berkeley, McGraw-Hill, 1998,Chapter 5.

• G. Blank and R. Barnes, The Universal Machine

 

, Boston, MA: WCB/ 

McGraw-Hill, 1998. Chapter 11.


Recommended