Array
Array
• C++ provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type.
• An array is used to store a collection of data, but it is often more useful to think
of an array as a collection of variables of the same data type.
• The total number of elements in the array is called the length.
• The elements of array is accessed with reference to its position in array, that is
called index or subscript.
Advantages of Array
• One-dimensional Array
• Two-dimensional Array
• Multi-dimensional Array
One-dimensional Array
• A one-dimensional array (single-dimensional array) is an array in which the components are
arranged in a list form.
• The general form for declaring an one-dimensional array is
datatype Identifier[intExp];
Identifier[intexExp];
both arrays are of same data type and have same number of components.
To copy one array into another array, you must copy it component wise i.e. one component at a
time.
for(int i = 0; i < 5; i++)
finalmarks[i] = marks[i];
Some Restriction on Array Processing
• To read the data into the array:
The statement cin >> finalmarks; is illegal and it generates a syntax error.
To read data into finalmarks, you must read one component at a time, using a loop such as
for(int i = 0; i < 5; i++)
cin>> finalmarks[i];
here, marks[0] = 56.6, marks[1] = 75, marks[2] = 65.4, marks[3] = 76.4 and marks[4] = 54.3
• The number of values between braces { } can not be larger than the number of elements
that we declare for the array between square brackets [ ].
• It is not necessary to specify the size of the array if it is initialized during declaration.
• The above statement is equivalent to
The function functionName has two parameters: (1) listOne, a one-dimensional array of type int
and (2) listTwo, a one-dimensional array of type double. In this declaration, the size of both array is
unspecified.
Array as Parameters to Functions
• Sometimes, the number of elements in the array might be less than the size of the array.
• Example:
The number of elements in an array storing student data might increase or decrease as
students add or drop courses.
In such situations, we want to process only the components of the array that holds actual
data.
To write a function to process such array, we will declare an array as a formal parameter
along with another formal parameter that specify the size of array.
The first parameter of the function functionName is an int array of any size. When the
function is called, the size of the actual name is passed as a second parameter of the
function.
Constant Array as a formal Parameters
• When the formal parameter is a reference parameter, then whenever the formal parameter
changes, the actual parameter changes as well.
• If you do not want the function to modify the array, then one can use a reserved word const in
the declaration of the formal parameter in the function definition to keep an array unchanged.
• Example:
• Here, the function example can modify the array x, but not the array y. Any attempt to change y
results in a compile-time error.
Example
C++ does not allow functions to return a value of the type array.
Here, the function sumArray returns value of type int
EXAMPLE
• C++ provides more flexibility by allowing an index to be of any
integral type or enumeration type.
• This flexibility can greatly enhance a program’s readability.
• Example:
Typedef with Arrays
• Using typedef, one can also defined the array.
• typedef is used to give a name to an array type.
• Example:
typedef double list[50];
list yourlist;
list mylist;
• In the first line of the example, we have defined a data type list, which is an
array of 50 components of type double.
• In the second and third line of the example, we have declared two variables
yourlist and mylist. Both are arrays of 50 components of type double.
• The example is equivalent to
double yourlist[50];
double mylist[50];
C-STRINGS (CHARACTER ARRAYS)
• Definition:-
An array, whose components are of type char, is called character array.
• The first character in the ASCII character set is null character, which is non-printable
and it is represented as ‘\0’, a backlash followed by a zero.
• The statement:
ch = ‘\0’;
stores the null character in ch, where ch is a char variable.
• The collating sequence of the null character is 0, the null character is less than any
other character in the char data set.
C-STRINGS (CHARACTER ARRAYS)
• The most commonly used term for character array is C-strings.
• In C++, the collection of characters is stored in the form of arrays. Hence, it is called C-strings.
• C-strings are arrays of type char terminated with null character, that is, \0, (ASCII value of null character
is 0).
• However, there is little difference between the character array and C-strings
In C++, C-strings are always null terminated i.e. the last character in a C-string is always the null
character. While, a character array might not contain the null character.
The null character should not appears anywhere in the C-string except the last position.
The C-strings are stored in (one-dimensional) character arrays.
Example:-
There is a difference between ‘A’ and “A”. The ‘A’ is a character A and “A” is C-string A. Because, C-
strings are null terminated, “A” represents two characters: ‘A’ and ‘\0’. So, to store the C-string “A”
in computer memory, we need two memory cells to type char.
Example:
char name[5] = “JOHN”;
In the above code, name, is a C-string and it holds 5 characters, including the null character.
Although, name has 4 character and the null character ,\0, is added to the end of the C-string
automatically.
C-STRINGS (CHARACTER ARRAYS)
• Alternative ways of defining a C-string
char name[] = “JOHN”;
char name[] = {‘J’, ‘O’, ‘H’, ‘N’};
char name[5] = {‘J’, ‘O’, ‘H’, ‘N’};
Here, all declarations are equivalent.
• Like arrays, it is not necessary to use all the space allocated for the C-string
The statement: char name[16]; declares an array name of 16 components of type char. Because,
the C-strings are null terminated and the length of name array is 16, so, the largest string that can
be stored in the name array would be of length 15.
If you store C-string of length 9 in name array, the first 10 components of name array are used and
the last six are left unused.
C-STRINGS (CHARACTER ARRAYS)
• C++ provides a set of functions that can be used for C-string manipulation.
To copy a C-string into another C-string: strcpy (string copy) function can be used.
To compare C-string: strcmp (string comparison) function can be used.
To find the length of C-string: strlen (string length) function can be used.
• To use these functions, the program must include the header file cstring via the include statement, i.e.
#include <cstring>
• In C++, the C-strings are compared character-by-character using the system’s collating sequence.
Function Effect
strcpy(s1, s2) Copies the string s2 into the string variable s1.
The length of s1 should be at least as large as s2.
strcmp(s1, s2) Returns a value < 0 if s1 is less than s2
Returns 0 if s1 and s2 are same
Returns a value > 0 if s1 is greater than s2
strlen(s) Returns the length of the string s, excluding the null character.
EXAMPLE
Reading and Writing Strings
• Aggregate operations, such as assignment and comparison, are not allowed on arrays.
Even, the input/output of arrays is done by component wise.
• In the case of C-string (character array), C++ allows aggregate operation such as input
and output.
• Consider, the following statement:
char name[31];
Reading and Writing Strings
String Input:
• Because aggregate operation are allowed for C-string input, the statement:
cin >> name;
stores the next input C-string into name.
• The length of the input C-string must be less than or equal to 30. If the length of
input string is 4, then computer stores the four characters that are input and the null
character ‘/0’.
• If the length of the input C-string is more than 30, then because there is no check on
the array index bounds, the computer continues storing the string in whatever
memory cells follow name. This process can cause serious problems, because data in
the adjacent memory cells will be corrupts.
• We know that the extraction operator ,>>, skips all leading whitespace characters and
stops reading data into the current variable as soon as it finds the first whitespace
character or invalid data. As a result, C-strings that contain blanks can not be read
using the extraction operator ,>>,
Reading and Writing Strings
String Input:
• The get function can be used to read C-strings.
• In the case of C-string, get function that has two parameters. The first parameter is a
C-string variable, the second parameter specifies how many characters to read into
string variables.
• The general syntax for get function to read C-strings is
cin.get(str, m+1);
This statement stores the next m characters or all characters until the newline
character ‘/n’ is found into str.
The newline character is not stored in str.
If the input C-string has fewer than m characters, then the reading stops at the
newline character.
Reading and Writing Strings
String Output:
• The output of C-strings is another place where aggregate operations on arrays are
allowed.
• One can output C-string by using an output stream variable, such as cout, together
with the insertion operator, << .
• The statement:
cout << name;
outputs the contents of the 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 you will see strange output because
the insertion operator continues to output data from memory adjacent to name until
‘\0’ is found.
TWO-DIMENSIONAL ARRAYS
TWO-DIMENSIONAL ARRAYS
datatype arrayName[intExp1][intExp2];
where intExp1 and intExp2 are constant expressions have positive integers values.
The expressions intExp1 and intExp2, specify the number of rows and the number
of columns, respectively, in the array.
TWO-DIMENSIONAL ARRAYS
• Example: The statement:
double sales[5][8];
[1]
[2]
[3]
[4]
Accessing Array Components:
• To access the components of a two-dimensional array, a pair of indices is needed: one for the row
position and one for the column position.
• The syntax: To access the two-dimensional array, the general syntax is
arrayName[indexExp1][indexExp2];
where indexExp1 and indexExp2 are constant expressions yielding non-negative integers values.
The expressions indexExp1 and indexExp2, specify the position rows and the columns, respectively.
• Example: The statement: sales[3][6] = 25.67; stores 25.67 into row number 3 and column number 6.
[1]
[2]
[3] 25.67
[4]
Accessing Array Components:
• Suppose that
int i = 3;
int j = 6;
Then the statement
sales[3][6] = 25.67;
is equivalent to
sales[i][j] = 25.67;
• Example:
int board[4][3] = {{2, 3, 4}, {4, 5, 6}, {5, 6, 7}, {6, 7, 8}}
This statement declares board to be a two-dimensional array of four rows and three columns. The
components of first row are 2, 3 and 4; the components of second row are 4, 5 and 6; the components of
third row are 5 , 6 and 7; the components of fourth row are 6, 7 and 8.
[1] 4 5 6
[2] 5 6 7
[3] 6 7 8
Two-dimensional Array Initialization During
Declaration
[FORD] 4 5 6
[TOYOTA] 5 6 7
[BMW] 6 7 8
Processing Two-dimensional Array
• A two-dimensional array can be processed in three ways:
Process the entire array.
Process a particular row of the array, called row processing.
Process a particular column of the array, called column processing.
• Initializing and printing the array are examples of processing the entire two-dimensional array.
• Finding the largest (smallest) element in a row (column) or finding the sum of a row (column) are
examples of row (column) processing.
• Because, the components of a two-dimensional array are of the same type, the components of any
row or column are of the same type.
• Each row and each column of a two-dimensional array is an one-dimensional array.
• Therefore, to process a particular row or column of a two-dimensional array, the algorithm similar
to those that process one-dimensional array can be used.
Example
• const int NUMBER_OF_ROWS = 5; const int NUMBER_OF_COLS = 4;
int matrix[NUMBER_OF_ROWS][NUMBER_OF_COLS];
int row, col sum, largest, temp;
• To process row number 3 of the matrix (that is the fourth row of the matrix). The components of
this row are
matrix[3][0], matrix[3][1], matrix [3][2], matrix[3][3]
row = 3;
for(col = 0; col < NUMBER_OF_COLS; col++)
matrix[row][col] = 0;
row = 3;
for(col = 0; col < NUMBER_OF_COLS; col++)
cout << matrix[row][col] << “ ”;
• To print the data into a particular row (consider row = 2, i.e. third row)
row = 3;
for(col = 0; col < NUMBER_OF_COLS; col++)
cin >> matrix[row][col] ;
• To input the data into a particular row (consider row = 2, i.e. third row)
for(row = 0; row < NUMBER_OF_ROWS; row++)
{
for(col = 0; col < NUMBER_OF_COLS; col++)
{
cin >> matrix[row][col];
}
}
Sum by Row
row = 3;
sum = 0;
for(col = 0; col < NUMBER_OF_COLS; col++)
sum = sum + matrix[row][col];
col = 2;
sum = 0;
for(row = 0; row < NUMBER_OF_ROWS; row++)
sum = sum + matrix[row][col];
This function takes as a parameter a two-dimensional array of an unspecified number of rows and five columns,
and outputs the content of the two-dimensional array. During the function call, the number of columns of the
actual parameters must match the number of columns of the formal parameter.
Array of strings
the above array can hold a list of up to 4 C-strings (representing here the names of scientists),
and each C-string can have up to 9 characters.
• An array of C-strings can be manipulated by using both indexes simultaneously like any other
two-dimensional arrays.
• It is better to manipulate it by a loop that steps through the first index and treats each indexed
variable as a single C-string variable that is manipulated by some C-string function.
Exercise
• Enter 10 integers into an array and short them in an ascending/ descending
order.
• Enter 10 integers into an array and then search for a particular integer in
the array.
• Enter 10 integers into an array and then find the smallest and largest
element in the array.
• Addition and subtraction of two matrices using two-dimensional arrays.
• Multiplication of two matrices using two-dimensional arrays.
• Find the transpose of any two-dimensional array.
• Using arrays, read the vectors of the following type: A = (1 2 3 4 5 6 7 8) , B
= (0 2 3 4 0 1 5 6 ) and compute the product and addition of these vectors.