Arrays and Strings
IIT [Delhi]
"All students to receive
arrays!" reports Dr. Austin.
Declaring arrays
Passing arrays
as parameters
Inspecting arrays
scores
scores:: 85
85 79
79 92
92 57
57 68
68 80
80 ......
0 1 2 3 4
5
98 99
Simple vs Structured Data
Types
Simple data type => data element
contains a single value
xx::15
15
avg
avg::84.35
84.35
ch
ch::A
A
Structured data type => a data element
contains a collection of data values
scores
scores:: 85
85 79
79 92
92 57
57 68
68 80
80
name
name:: C
C L
L Y
Y D
D E
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
scores
scores:: 85
85 79
79 92
92 57
57 68
68 80
80
0 1 2 3 4
5
cout
cout <<
<< scores[2];
scores[2];
scores[0]
scores[0] == 100;
100;
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
Notedeclaration
declaration
Declaring Arrays
Syntax:
Data_type Array_name [constant];
Note declaration from our example
Tells
Tellshow
howmany
manyelements
elementsset
setaside
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
scores:: 85
85 79
79 92
92 57
57 68
68 80
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
scores:: 85
85 79
79 92
92 57
57 68
68 80
80 ......
0 1 2 3 4
5
Index
Indexcan
canbe:
be:
--constant
constant
--variable
variable
--expression
expression
MUST
MUSTbe
bean
aninteger
integer
98 99
max
max == scores[0];
scores[0];
for
for (x
(x == 0;
0; xx << 100;
100; x++)
x++)
if
if (scores[x]
(scores[x] >> max)
max)
max
max == scores[x];
scores[x];
Initializing Arrays in
Declarations
10
Possible to declare the size & initialize
int
int results
results [5]
[5] == {14,
{14, 6,
6, 23,
23, 8,
8, 12
12 }}
Possible to omit size at declaration
Compiler figures out size of array
float
float prices
prices [[ ]] == {{ 2.41,
2.41, 85.06,
85.06, 19.95,
19.95, 3.91
3.91 }}
11
Arrays as Parameters
This is one task that CAN be done to the
WHOLE array
C++ always passes arrays by reference
12
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
13
Arrays as Parameters
Note the empty brackets in parameter
list
A number can be placed here but it
will be
ignored
14
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 = dont do it;
15
String Output
Strings (character arrays) are handled
differently than other types of arrays
This would NOT be allowed
This is legal:
int
int num_list
num_list [100];
[100];
.. .. ..
cout
cout <<
<< num_list;
num_list;
char
char name
name [30]
[30] == Snidly
Snidly Q.
Q. Fizbane;
Fizbane;
.. .. ..
cout
cout <<
<< name;
name;
16
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
17
Using Strings
Instead of hard coding file name for
the open ( ) command,
use a string variable,
use keyboard entry with
cin.getline()
ifstream
ifstream inFile;
inFile;
char
program
more flexible, good for
fname[31];
char
fname[31];
cout
<<
cout
<< Enter
Enter
file name
name ->
-> ;
;
different
files file
cin.getline
cin.getline (fname,
(fname, 30,
30, \n);
\n);
inFile.open
inFile.open (fname);
(fname);
18
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 CStrings
Assignment is OK
string s;
s = "hi mom";
Comparison OK
if (s < "geek")
I/O allowed
cin >> s;
cin.getline(s,'\n');
cout << s;
19
Assignment is illegal
char cs[30];
cs = "don't do it";
Comparisons not allowed
I/O allowed much the
same way
20
Working with C-Strings
Functions provided in #include
<cstring>
Used instead of assignment
Used for comparisons
21
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
22
23
Design Problem
Consider the task of
keeping track of data
about parts for
manufacture
part number,
description, qty
needed, unit price
24
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
1.23
23
8.95
B25
xxx
yyy
Testing and Debugging
Hints
25
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
26
Omitting array size in declaration
when array declared formal parameter
when array initialized at declaration
Dont 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
27
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
28
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
29
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