4.1 Introducing arrays:
An array is a data form that can hold several values,
all of one type. Arrays are like structures in that they both group a number of
items into a larger unit. But while a
structure usually groups items of different types, an array groups items of the
same type. More importantly, the items
in a structure are accessed by an index number. Using an index number to
specify an item allows easy access to a larger number of items.
To create an array, you use a declaration statement.
An array declaration should indicate three things:
·
The
type of value to be stored in each statement.
·
The
name of the array
·
The
number of elements in the array
You
accomplish this in C++ by modifying the declaration for a simple variable,
adding brackets that contain the number of elements. For example, the
declaration
short months[12]; //creates array of 12 short
creates an array named months that has 12 elements,
each of which can hold a type short value.
Each element, in essence, is a variable that you can treat as a simple
variable. The general form for declaring an array is this:
typeName arrayName[arraySize];
The expression arraySize,
which is the number of elements, must be a constant, such as 10 or a const
value, or a constant expression, such as 8 * sizeof (int), for which all values
are known at the time compilation takes place. In particular, arraySize, cannot be a variable whose
value is set while the program is running.
An array is derived type because it is based on some
other type. You can’t simply declare that something is an array; it always has
to be an array of some particular type. There is no generalized array type.
Instead, there are many specific array types, such as array of char or array of
long.
4.2 Array Elements:
The items in an array are called elements (in contrast
to the items in a structure, which are called members.) As we noted, all the
elements in an array are of the same type; only the values vary.
4.3 Array Initialization:
C++ has several rules about initializing an array.
They restrict when you can do it, and they determine what happens if the number
of array elements doesn’t match the number of values in the initializer.
You can use the initialization form only when defining
the array. You cannot use it later, and you cannot assign one array wholesale
to another.
int cards[4] = { 3,6,8,10} //ok
int cards[4] =
{3, 6, 8, 10}; // okay
int hand[4]; // okay
hand[4] = {5, 6,
7, 9}; // not allowed
hand = cards; // not allowed
However, you can
use subscripts and assign values to the elements of an array individually. When
initializing an array, you can provide fewer values than array elements. For
example the following statement initializes only the first two elements of
hotel Tips:
float
hotelTips[5] = {5.0, 2.5};
If you partially
initialize an array, the compiler sets the remaining elements to zero. Thus,
its easy to initialize all the elements of an array to zero, just initialize
the first element explicitly to zero and then let the compiler initialize the
remaining elements to zero:
float
totals[500] = {0};
If you leave the
square brackets empty when you initialize an array, the C++ compiler counts the elements for you. Suppose, for example, you
make this declaration:
short things[ ] = {1, 5, 3, 8};
The compiler
makes things an array of four elements.
// shows days
from start of year to date specified.
#
include<iostream.h>
void main( )
{
int month, day,
tot_days;
int
days_p_m[12]={31, 28, 31, 30, 31, 30,
31, 31,30, 31, 30, 31};
cout<<”
\nEnter month”; //get date
cin>>month;
cout<<”Enter
day”;
cin>>day;
tot_days=day;
for (int j=0;
j<month-1; j++)
tot_days += days_p_m[j];
cout<<”Total
days from start of year is:” <<tot_days;
}
The program
calculates the number of days from the beginning of the year to a date
specified by the user.
4.4 Two-Dimensional Array:
You can
visualize the 2 dimensional array, which looks like a table having both rows
and columns. C++ doesn’t provide a special two-dimensional array type. Instead, you create an array for which each
element is itself an array. For example
int
maxtemps[4][5];
This declaration
means that maxtemps is an array with four elements. Each of these elements is
an array of five integers. Thus you need two subscripts to access the int
elements. You can think of the first subscripts to access row and the second as
column.
Initializing a two – Dimensional array: For a two-dimensional array, each element
is itself an array, so you can initialize each element by using a form like the
single dimension array. Thus initialization consists of a comma separated
series of one-dimensional initializations all enclosed in a set of braces:
int
maxtemps[4][5] =
{
{4, 56, 76, 77, 101}, // values for maxtemps[0]
{34, 6, 90,45, 244}, // values for maxtemps[1]
{24, 456, 68, 9, 12}, // values for maxtemps[2]
{86, 305, 23, 59, 104} // values for
maxtemps[3]
};
The term {4, 56,
76, 77, 101} initializes the first row, represented by maxtemps[0]. As a matter
of style, placing each row of data on its own line, if possible, makes the data
easier to read.
4.5 Passing Arrays To Functions:
Arrays can be
used as arguments to functions. Pass an ordinary variable, and the function
works with a copy. But pass an array, and the function works with the original.
The difference doesn’t violate C++’s pass-by-value approach. The design
decision to use array addresses as arguments saves the time and memory needed
to copy the entire array.
// passes array
as argument
# include
<iostream.h>
# include
<iomanip.h>
const int
DISTRICTS = 4;
const int MONTHS
= 3;
void display(
float[DISTRICTS][MONTHS] );
void main( )
{
float
sales[DISTRICTS][MONTHS] = { { 1432.07, 234.50, 654.01 },
{ 322.00, 13838.32, 17589.88 },
{ 9328.34, 934.00, 4492.30 },
{ 12838.29, 2332.63, 32.93}
};
display ( );
}
void display(
float funsales[DISTRICTS][MONTHS] )
{
int d, m;
cout <<
"\n\n" .
cout <<
"month\n”;
cout
<<" 1 2 3";
for(d=0;
d<DISTRICTS; d++)
{
cout
<<"\nDistrict " << d+1;
for(m = 0;
m<MONTHS; m++)
cout
<< setw(10) << setprecision(2) << funsales[d][m];
}
}
4.6 Arrays of Structures:
Arrays can
contain structures as well as simple data types. To initialize an array of
structures, combine the rule for initializing arrays with the rule for
structures. Because each element of the array is a structure, its value is
represented by a structure initialization.
# include
<iostream.h>
const int SIZE =
4;
struct part
{
int modelnumber;
int
partnumber;
float cost;
};
void main( )
{
int n;
part
apart[SIZE];
for(n=0;
n<SIZE; n++)
{
cut
<< endl;
cout
<<"Enter modelnumber";
cin
>> apart[n]. mnum;
cout
<< "Enter part number";
cin
>> apart[n].pnumb;
cout
<< "Enter cost";
cin
>> apart[n].cost;
}
for(n=0;
n<SIZE; n++) //show value for
all member
{
cout
<< "\nModel " << apart[n].mnum;
cout
<< "\nPart << apart[n].pnumb;
cout
<< " Cost " << apart[n].cost;
}
}
The user types
in the model number, part number, and cost of a part. The program records this
data in a structure. However, this structure is only one element in an array of
structures. The program asks for the data for four different parts, and stores
it in the four elements of the apart array. It then displays the
information:
The array of
structures is defined in the statement,
part apart
[SIZE];
This has the
same syntax as that of arrays of simple data types. Only the type name, part shows that this is an array of a
more complex type.
Accessing a data
item that is a member of a structure that is itself an element of an array
involves a new syntax. For example,
Apart[n].modelnumber;
refers to the
modelnumber member of the structure that
is element n of the apart array.
4.7 Arrays Of Objects:
We can create an
array of objects. Consider the following program.
# include
<iostream.h>
const int MAX =
100; // maximum
number of elements
class Distance
{
private:
int feet;
float
inches;
public:
void
getdist ( )
{
cout << "\n Enter feet: "; cin >> feet;
cout << " Enter inches: "; cin >> inches;
void
showdist( )
{ cout << feet <<
"\’-" << inches << ‘\ "' ;}
};
void main( )
{
Distance
dist[MAX]; //array
of distances
int n = 0; II count the entries
char ans; II user response ('y' or 'n')
cout <<
endl;
do {
cout
<< "Enter distance number " « n+1 ;
dist[n++].getdist(
); II store distance in array
cout
<< "Enter another (yln)?: ";
cin
>> ans;
}while( ans != 'n' );
for(int j = 0; j
< n; j ++) II display all distances
{
cout
<< "\nDistance number " << j+1 << " is ";
dist[j].showdist(
);
}
}
In this program
the user types in as many distances as desired. After each distance is entered,
the program asks if the user desires to enter another. If not, it terminates,
and displays all the distances entered so far.
A class member
function that is an array element is accessed similarly to a structure member
that is an array element. The showdist(
) member function of the jth
element of the array dist is invoked
dist[j].showdist( );
as you can see,
a member function of an object that is an array element is accessed using the
dot operator, to the member function name followed by parentheses. This is
similar to accessing a structure (or class) data member, except that the
function name an parenthesis are used instead of the data name.
4.8 String Variables:
Array can be created
of any data type. Here's an example that defines a single string variable. It
asks the user to enter a string and places this string in the string variable.
Then it displays the string.
# include
<iostream.h>
const int MAX = 80; // max characters in string
void main( )
{
char str[MAX]; // string variable str
cout << "\nEnter a string:
";
cin >> str;
cout << "You entered: "
<< str;
}
The definition of the
string variable str looks like the
definition of any array of type char
:
char
str[MAX];
We use the insertion
operator >> to read a string
from the keyboard and place it in the string variable str: This operator knows how to deal with strings; it understands
that they are arrays of characters. Each
character occupies one byte of memory. An important aspect of strings in C++ is
that they must terminate with a byte containing 0. This is often represented by
the character constant ‘\0’, which
is a character with an ASCII value of 0.
This terminating zero is called the null character. When the <<
operator displays the string it displays characters until it encounters the
null character.
4.9 Arrays of Strings:
If there are arrays of arrays, of course there can be
arrays of strings. For example
# include <iostream.h>
const int DAYS = 7; //
number of strings in array
const int MAX = 10; //
maximum size of each string
void main( )
{
char star[DAYS][MAX] = { "Sunday",
"Monday", "Tuesday", "Wednesday",
"Thursday",
"Friday", "Saturday" };
for(int j=O; j<DAYS; j++)
cout
<< star[j] << endl;
}
The program prints out each string from the array:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Since a string is an array, it must be that
star - an array of strings-is really
a two-dimensional array. The first dimension of this array, DAYS, tells how many Strings are in the array. The second dimension, MAX specifies, the maximum length of the
string (9 character for "Wednesday" plus the terminating null makes
10).
Notice that some bytes are wasted following strings that are less than
the maximum length.
Exercise:
1. Write a function that reverses an
array of characters. The string should be passed as argument to the function.
Write a program, which accepts the array of characters from the user.
2. Create a class employee that
contains employee name and employee number. Include a function to get the data
from the user and another function to display the data. Write a program to
exercise this class. It should create an array of type employee and allow the
user to enter the details.
3. Write a program that uses the
following functions:
Fill_array( ) takes as arguments the name and
size of the array.
Show_array( ) takes as arguments the name and
size of the array and display’s the data.
Sort_array( ) takes as arguments the name and
size of the array and sort’s it.