0% found this document useful (0 votes)
19 views9 pages

Unit 3

This document provides an overview of arrays in C++, explaining their structure, declaration, and usage for storing multiple variables of the same type. It covers one-dimensional and two-dimensional arrays, including how to access and initialize them, as well as the concept of indexing. Additionally, it discusses the use of arrays for strings and multidimensional arrays, highlighting their applications in handling large data sets.

Uploaded by

d54308976
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views9 pages

Unit 3

This document provides an overview of arrays in C++, explaining their structure, declaration, and usage for storing multiple variables of the same type. It covers one-dimensional and two-dimensional arrays, including how to access and initialize them, as well as the concept of indexing. Additionally, it discusses the use of arrays for strings and multidimensional arrays, highlighting their applications in handling large data sets.

Uploaded by

d54308976
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

UNIT 3

ARRAYS IN C++
3.0 INTRODUCTION
Society today generates massive amounts of data, including records of digital transactions, social
media posts, and information from sensors and devices spread everywhere. In order to handle that
large amount of data, we need a way to store it. And we need to be able to store not just a few
variables, but dozens, or hundreds, or thousands. Fortunately, there's a solution—in fact, more than
one solution—for handling as much data as you have. Two methods for storing
data are arrays, which were part of C, and vectors, which were an improvement of C++.
An array is a sequence of objects all of which have the same type. The objects are called the
elements of the array and are numbered consecutively 0, 1, 2, 3, ... . These numbers are called
index values or subscripts of the array. The term “subscript” is used because as a mathematical
sequence, an array would be written with subscripts: a0, a1, a2, …. The subscripts locate the
element’s position within the array, thereby giving direct access into the array.
If the name of the array is a, then a[0] is the name of the element that is in position 0, a[1]
is the name of the element that is in position 1, etc. In general, the ith element is in position i–1.
So if the array has n elements, their names are a[0], a[1], a[2], …, a[n-1].

3.1 STORING VARIABLES IN MEMORY


Let's say that you want to store one variable. You declare a variable, and that creates a "box" with
that variable name that's stored in memory. If you want to store a second variable, you declare a
second variable, which gets a new box in memory.
If you wanted to allocate many variables—say20 of them—it would be painful to declare 20
different variables. Instead, it would be easier to say, "I want a set of 20 variables"—and that's
what an array gives you.
An array is a collection of some number of variables. All the variables will have the same type,
and all will be referred to using the same name, with a separate way of identifying each individual
variable.
To declare an array of variables, you still start with the type of variable you want. In this example
below, it's an integer but it could also be any of the datatypes we know.
You then have the name of the array, which is test_array. It wouldn't be practical to name all the
variables with different names, so you refer to the entire group—the entire array—by one name.
After the array name, you have a pair of square brackets, which let you specify the size of the
array, or the number of elements in the array. In this case, you're setting up an array of size 20.
In mathematics, vectors and matrices are described using square brackets. Because an array is
similar to a vector or matrix in math, it makes sense that square brackets are used for them, too. In
1|Page
memory, these 20 "boxes" are all set aside in one big block—one block right after another.
After the array has been declared—that is, after that long stretch of boxes has been set aside in
memory—you can refer to each individual box as a separate variable. To do this, you will again
use square brackets, each containing a number, after the array name. The first such box will be 0,
the second one will be 1, etc. You refer to a box by the array name and then, in square brackets,
the box number.
In Program 3_1, you are assigning values of 10, 20, and 25 to the first 3 boxes in the array.
Notice that you can assign values to them, and you can refer to the values inside them, just like
with other variables.
1 // Program 3_1
2 // Declaring an array
3 #include <iostream>
4 using namespace std;
5 int main() {
6 int test_array[20];
7 test_array[0] = 10;
8 test_array[1] = 20;
9 test_array[2] = 25;
10 cout << test_array[0] << " " << test_array[1] << " " << test_array[2] << endl;
11 return 0
12 }
Let us look another example of arrays using the code below;
1 #include <iostream>
2 using namespace std;
3 int main ()
4 { double a[3];
5 a[2] = 55.55;
6 a[0] = 11.11;
7 a[1] = 33.33;
8 cout << "a[0] = " << a[0] << endl;
9 cout << "a[1] = " << a[1] << endl;
10 cout << "a[2] = " << a[2] << endl;
11 return 0
12 }

Generally, the whole array is referred to as the variable. In other words, even though the array is
made up of many different "boxes", which you could think of as many different individual
variables, you will generally be able to refer to the entire array—the entire collection of boxes—
as one thing, so it makes sense to call it a variable. The individual boxes are called the elements,

2|Page
which are the component variables of the overall array variable. The number identifying an
element is called the index. To refer to an element of the array, the common phrase used is sub
(which can be thought of as short for subscript) and then the index number.

3.2 INDEXING INTO AN ARRAY


One of the things that makes using arrays feasible is that you can use a variable to represent the
individual index. Suppose you create a small array named a with 5 elements, and suppose you
assign values of 10, 20, 30, 40, and 50 to them. Then, you create an integer index variable i that
you initialize to 3, and you print out a[i]
#include <iostream>
using namespace std;
int main() {
int a[5];
a[0]=10; a[1]=20; a[2]=30; a[3]=40; a[4]=50;
int i = 3;
cout << a[i] << endl;
return 0;
}
The output is the value that you assigned to a[3], which was 40
When you access a single element of the array—by listing the array name and then putting the
particular element index in square brackets—you are said to be indexing into the array. In other
words, you're accessing array elements using the index of an element. The ability to index into
an array by using a variable that contains the index gives you the ability to easily address all the
elements of the array by looping through it.

3.3 INITIALIZING AN ARRAY


Like any other simple variable, an array can be initialized while it is being declared. For
example, the following C++ statement declares an array, sales, of five components and
initializes these components.
double sales[5] = {12.25, 32.50, 16.90, 23, 45.68};
The values are placed between curly braces and separated by commas—here,
sales[0] = 12.25, sales[1] = 32.50, sales[2] = 16.90, sales[3] = 23.00,
and sales[4] = 45.68.
When initializing arrays as they are declared, it is not necessary to specify the size of the
array. The size is determined by the number of initial values in the braces. However, you
must include the brackets following the array name. The previous statement is, therefore,

3|Page
equivalent to:
double sales[] = {12.25, 32.50, 16.90, 23, 45.68};

3.4 TWO AND MULTIDIMENSIONAL ARRAYS AND VECTORS


In the previous sections of this unit, we introduced arrays that were in one dimension and use then
to store sequence of values. Each of the containers considered in that section had one dimension:
its length, which is the number of values in the sequence.
In the previous section, you learned how to use one-dimensional arrays to manipulate
data. If the data is provided in a list form, you can use one-dimensional arrays. However,
sometimes data is provided in a table form. For example, suppose that you want to track
the number of cars in a particular color that are in stock at a local dealership. The
dealership sells six types of cars in five different colors. Figure below shows sample data

You can see that the data is in a table format. The table has 30 entries, and every entry is an
integer. Because the table entries are all of the same type, you can declare a one-dimensional
array of 30 components of type int. The first five components of the one-dimensional array can
store the data of the first row of the table, the next five components of the one-dimensional array
can store the data of the second row of the table, and so on. In other
words, you can simulate the data given in a table format in a one-dimensional array.
If you do so, the algorithms to manipulate the data in the one-dimensional array will be somewhat
complicated, because you must know where one row ends and another begins.
You must also correctly compute the index of a particular element. C++ simplifies the
processing of manipulating data in a table form with the use of two-dimensional arrays.
This section first discusses how to declare two-dimensional arrays and then looks at ways
to manipulate data in a two-dimensional array.
Two-dimensional array: A collection of a fixed number of components arranged in rows
and columns (that is, in two dimensions), wherein all components are of the same type.
The syntax for declaring a two-dimensional array is:

4|Page
wherein intExp1 and intExp2 are constant expressions yielding positive integer values.
The two expressions, intExp1 and intExp2, specify the number of rows and the
number of columns, respectively, in the array.
The statement:
double sales[10][5];

declares a two-dimensional array sale of 10 rows and 5 columns, in which every


component is of type double. As in the case of a one-dimensional array, the rows are
numbered 0. . .9 and the columns are numbered 0. . .4 as shown below

3.5 ACCESSING ARRAY COMPONENTS


To access the components of a two-dimensional array, you need a pair of indices: one for the row
position and one for the column position.
The syntax to access a component of a two-dimensional array is:

wherein indexExp1 and indexExp2 are expressions yielding nonnegative integer values.
indexExp1 specifies the row position; indexExp2 specifies the column position.
The statement:
sales[5][3] = 25.75;
stores 25.75 into row number 5 and column number 3 (that is, the sixth row and the fourth column)
of the array sales.

5|Page
Suppose that:
int i = 5;
int j = 3;
Then, the previous statement:
sales[5][3] = 25.75;
is equivalent to:
sales[i][j] = 25.75;
So the indices can also be variables.

3.6 TWO-DIMENSIONAL ARRAY INITIALIZATION DECLARATION


Like one-dimensional arrays, two-dimensional arrays can be initialized when they are declared.
The following example helps illustrate this concept. Consider the following statement:

This statement declares board to be a two-dimensional array of four rows and three columns. The
components of the first row are 2, 3, and 1; the components of the second row are 15, 25, and 13;
the components of the third row are 20, 4, and 7; and the components of the fourth row are 11,
18, and 14, respectively.

To initialize a two-dimensional array when it is declared:


1. The elements of each row are enclosed within curly braces and separated by commas.
2. All rows are enclosed within curly braces.
3. For number arrays, if all components of a row are not specified, the unspecified components

6|Page
are initialized to 0. In this case, at least one of the values must be given to initialize all the
components of a row.

3.7 ARRAYS OF STRINGS


Suppose that you need to perform an operation, such as alphabetizing a list of names. Because
every name is a string, a convenient way to store the list of names is to use an array. Strings in
C++ can be manipulated using either the data type string or character arrays (C-strings).
Processing a list of strings using the data type string is straightforward. Suppose that the
list consists of a maximum of 100 names. You can declare an array of 100 components of
type string as follows:

Basic operations, such as assignment, comparison, and input/output, can be performed on


values of the string type. Therefore, the data in list can be processed just like any
one-dimensional array discussed earlier.
Suppose that the largest string (for example, name) in your list is 15 characters long and
your list has 100 strings. You can declare a two-dimensional array of characters of
100 rows and 16 columns as follows

3.8 MULTIDIMENSIONAL ARRAYS


In this chapter, we defined an array as a collection of a fixed number of elements (called
components) of the same type. A one-dimensional array is an array in which the elements are
arranged in a list form; in a two-dimensional array, the elements are arranged in a table form. We
can also define three-dimensional or larger arrays. In C++, there is no limit on the dimension of
arrays. Following is the general definition of an array.
The general syntax for declaring an n-dimensional array is:

7|Page
where intExp1, intExp2, . . . , and intExpn are constant expressions yielding
positive integer values.
For example, the statement:

declares carDealers to be a three-dimensional array. The size of the first dimension is 10, the size
of the second dimension is 5, and the size of the third
dimension is 7. The first-dimension ranges from 0 to 9, the second dimension
ranges from 0 to 4, and the third-dimension ranges from 0 to 6. The base address
of the array carDealers is the address of the first array component that is, the
address of carDealers [0][0][0]. The total number of components in the array
carDealers is 10 * 5 * 7 = 350
The statement:

sets the value of the component carDealers [5][3][2] to 15564.75


You can use loops to process multidimensional arrays. For example, the nested for
loops:

initialize the entire array to 0.0.

SELF ASSESMENT
1.Consider the following declaration: double salary[10];
In this declaration, identify the following:
a. The array name.
b. The array size.
c. The data type of each array component.
d. The range of values for the index of the array.
2. What would be a valid range for the index of an array of size 50?

8|Page
3. Write C++ statements to do the following:
a. Declare an array alpha of 15 components of type int.
b. Output the value of the tenth component of the array alpha.
c. Set the value of the fifth component of the array alpha to 35.
d. Set the value of the ninth component of the array alpha to the sum of the sixth and thirteenth
components of the array alpha.
e. Set the value of the fourth component of the array alpha to three times the value of the eighth
component minus 57.
f. Output alpha so that five components per line are printed.
4. Write C++ statements to define and initialize the following arrays.
a. Array heights of 10 components of type double. Initialize this array
to the following values: 5.2, 6.3, 5.8, 4.9, 5.2, 5.7, 6.7, 7.1, 5.10, 6.0.
b. Array weights of 7 components of type int. Initialize this array to the
following values: 120, 125, 137, 140, 150, 180, 210.

9|Page

You might also like