Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Array

C++ provides a data structure called an array that stores a fixed number of elements of the same type. Arrays allow storing and accessing related data sequentially by index. The document discusses different types of arrays like one-dimensional, two-dimensional, and multi-dimensional arrays and covers array declaration, initialization, accessing elements, and passing arrays to functions.

Uploaded by

ashodhiya14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Array

C++ provides a data structure called an array that stores a fixed number of elements of the same type. Arrays allow storing and accessing related data sequentially by index. The document discusses different types of arrays like one-dimensional, two-dimensional, and multi-dimensional arrays and covers array declaration, initialization, accessing elements, and passing arrays to functions.

Uploaded by

ashodhiya14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

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

• Array can store a large number of value with single name


• The values stored in the array can be sorted easily.
• The search process can be applied on array easily.
• Arrays are used to process many values very easily and quickly.
Types 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];

 datatype :- Datatype of values to be stored in the array


 Identifier: The name of the array.
 intExp: Number of elements. It is a positive integer and indicates the length of the array.
• Example: The statement: num[0]
int num[5]; num[1]
 This declares an array num of five components.
num[2]
 Each component is of type int.
 The components are num[0], num[1], num[2], num[3]

num[3], num[4]. num[4]


Accessing Array Components:
• The general syntax for accessing an array components

Identifier[intexExp];

 indexExp ,called the index, is any expression whose value is a non-negative


integer.
 This indexExp specifies the position of the components in the array.
• In C++, [] is an operator, called the array subscripting operator.
• In C++, the array index starts at 0.
• In C++, the index expression is evaluated first, giving the position of the
component in the array.
Accessing Array Components:
• Consider the following statement:
double list[5];
This declares an array list of double data type and has 5 components. The components are list[0],
list[1], list[2], list[3] and list[4].
• The assignment statement:
list[3] = 0.98;
stores 0.98 in list[3], which is the fourth element of the array.
num[0]
num[0]
num[1]
num[1]
num[2]
num[2]
0.98 num[3]
num[3]
num[4]
num[4]
Some Restriction on Array Processing
• Consider the following statements:
int marks[5] = {45, 54, 76, 23, 59}; Declares and initializes the array marks
int finalmarks[5]; Declares the array finalmarks

both arrays are of same data type and have same number of components.

• To copy the elements of marks into the corresponding elements of finalmarks.

 The statement finalmarks = marks; generates a syntax error.

 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];

• To print the data:


 The statement cout << finalmarks; is illegal and it generates a syntax error.
 To print data of array finalmarks, you must print one component at a time, using a loop such as

for(int i = 0; i < 5; i++)


cout << finalmarks[i];
Array Index out of Bounds
• Consider the following statement:
double num[5];
int i;
The component num[i] is valid i.e., i is a valid index if i = 0, 1, 2,3, 4.
• The index of an array is in bounds if index >=0 and index < ARRAY_SIZE. If either index<0 or index >
ARRAY_INDEX, then we say that the index is out of bounds.
• C++ does not check whether the index value is within range i.e. between 0 and ARRAY_SIZE.
• If the index goes out of bounds and the program tries to access the component specified by the index,
then whatever memory location is indicated by the index is accessed.
• for(i = 0; i<=5; i++)
num[i] = 0;
When i becomes 5, the loop test condition i<=5 evaluates to true and the body if the loop executes,
which results in storing 0 in num[5]. But, logically, num[5] does not exist.
Array Initialization during Declaration
• The programmer can initialize C++ array elements either one by one or using a single
statement as follows:

double marks[5] = {56.6, 75, 65.4, 76.4, 54.3};

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

double marks[ ] = {56.6, 75, 65.4, 76.4, 54.3};


Partial Initialization of an Array during Declaration
• When you declare and initialize an array simultaneously, you do not need to initialize all
components of the array. This procedure is called partial initialization of an array during
declaration.
• The statement:

double marks[5] = {0};

declares marks to be an array of 5 components and initializes all the components to 0.


• The statement:

double marks[5] = {56.6, 75};

declares marks to be an array of 5 components, initializes marks[0] = 56.6, marks[1] = 75


and all other components initialize to 0.
Array as Parameters to functions
• In the C++, arrays are passed by reference only.
• Since arrays are passed by reference only, you do not use the symbol & when declaring an array
as a formal parameter.
• When declaring one-dimensional array as a formal parameter, the size of the array is usually
omitted.
• If you specify the size of an one-dimensional array when it is declared as a formal parameter, the
size is ignored by the compiler.
• Example:

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

• Definition: A collection of a fixed number of components arranged in rows and


columns, wherein all components are of the same type.

• The syntax: The syntax for declaring a two-dimensional array is

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];

declares a two-dimensional array sales of 5 rows and 8 columns, where every


components is of type double. The rows are numbered 0…4 and the columns are
numbered 0…7.
sales [0] [1] [2] [3] [4] [5] [6] [7]
[0]

[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.

sales [0] [1] [2] [3] [4] [5] [6] [7]


[0]

[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;

• The indices can also be variables.


Two-dimensional Array Initialization During
Declaration
• As like one-dimensional array, the two-dimensional array can also be initialization when they are declared.

• 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.

board [0] [1] [2]


[0] 2 3 4

[1] 4 5 6

[2] 5 6 7

[3] 6 7 8
Two-dimensional Array Initialization During
Declaration

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


 The elements of each row are enclosed within curly braces and separated by commas.
 All rows are enclosed within curly braces.
 For number arrays, if all components of a row are not specified, the unspecified components are
initialized to 0. In this case at least one of the values must be given to initialize all the
components of a row.
Two-dimensional Arrays And Enumeration Types
• Enumeration type can also be used for array indices.
• Example: enum carType{TATA, FORD, TOYOTA, BMW};
enum colorType{RED, BLUE, BLACK};
int inStock[NUMBER_OF_ROWS][NUMBER_OF_COLUMNS];
These statements define the carType and colorType enumeration types and define inStock as a two-
dimensional array of 4 rows and 3 columns.
• The statement:
inStock[1][2] = 6;
is equivalent to
inStock[FORD][BLACK] = 6;
inStock [RED] [BLUE] [BLACK]
[TATA] 2 3 4

[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]

matrix [0] [1] [2] [3]


[0] row = 3;
for(col = 0; col < NUMBER_OF_COLS; col++)
[1] process matrix[row][col];
[2]
[3] col = 2;
for(row = 0; row < NUMBER_OF_ROWS; col++)
[4] process matrix[row][col];
Initialization
• To initialize a particular row, consider row = 3 (fourth row):

row = 3;
for(col = 0; col < NUMBER_OF_COLS; col++)
matrix[row][col] = 0;

• To initialize a particular column, consider col = 2 (third column):


col = 2;
for(row = 0; row < NUMBER_OF_ROWS; row++)
matrix[row][col] = 0;

• To initialize the entire matrix:

for(row = 0; row < NUMBER_OF_ROWS; row++)


{
for(col = 0; col < NUMBER_OF_COLS; col++)
matrix[row][col] = 0;
}
Print
• To print a particular row, consider row = 3 (fourth row):

row = 3;
for(col = 0; col < NUMBER_OF_COLS; col++)
cout << matrix[row][col] << “ ”;

• To print a particular column, consider col = 2 (third column):


col = 2;
for(row = 0; row < NUMBER_OF_ROWS; row++)
cout << matrix[row][col] << endl;

• To print 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++)
{
cout << matrix[row][col] << “ ”;
}
cout << endl;
}
Input
• To input a particular row, consider row = 3 (fourth row):

row = 3;
for(col = 0; col < NUMBER_OF_COLS; col++)
cin >> matrix[row][col] ;

• To input a particular column, consider col = 2 (third column):


col = 2;
for(row = 0; row < NUMBER_OF_ROWS; row++)
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

• To sum the entries of a particular row, consider row = 3 (fourth row):

row = 3;
sum = 0;
for(col = 0; col < NUMBER_OF_COLS; col++)
sum = sum + matrix[row][col];

• To find the sum of entries of each row separately

for(row = 0; row < NUMBER_OF_ROWS; row++)


{
sum = 0;
for(col = 0; col < NUMBER_OF_COLS; col++)
sum = sum + matrix[row][col];
cout << “sum of row” << row +1 << “ = ” << sum << endl;
}
Sum by Column

• To sum the entries of a particular column, consider col = 2 (third column):

col = 2;
sum = 0;
for(row = 0; row < NUMBER_OF_ROWS; row++)
sum = sum + matrix[row][col];

• To find the sum of entries of each column separately

for(col = 0; col < NUMBER_OF_COLS; col++)


{
sum = 0;
for(row = 0; row < NUMBER_OF_ROWS; row++)
sum = sum + matrix[row][col];
cout << “sum of column” << col +1 << “ = ” << sum << endl;
}
Another way for defining Two-dimensional array

Passing Two-dimensional Arrays as parameters to
Functions
• Two-dimensional arrays can be passed as parameters to a function and they
are passed by reference.
• C++ uses the row form order to store a two-dimensional array, i.e., the first
row is stored first, followed by second row, followed by third row and so
on.
• Because C++ stores two-dimensional array in row order form, to compute
the address of a component correctly, the compiler must know where one
row ends and next row starts.
• To declare a two-dimensional array as a formal parameter, you can omit the
size of first dimension, but not the second, i.e., you must specify the number
of columns.
Passing Two-dimensional Arrays as parameters to
Functions

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

• Suppose that you need to perform an operation, such as


alphabetizing a list of name.
• Because every name is a string, a convenient way to store the list of
names is to use an any array.
• Strings in C++ can be manipulated using either the data type string or
character arrays (C-strings)
Array of strings and the string type
• In this method, size of the string is not fixed, hence space is saved.
• Syntax:
string list[length];
list is the name of array of string and length is the total number of strings that you
want to store in the list array.
• Consider the statement:
string list[50];
here the list consists of a maximum of 50 names.
• Basic operations, such as assignment, comparison and input/output can be
performed on value of the string type.
• The data in list can be processed just like any one-dimensional array.
• Drawback of this method is that the array is of fixed Size
EXAMPLE
Array of Strings and C-strings (character Arrays)
• Since C-strings are stored in single dimensional character arrays, an array of C-strings is
represented as a 2-D character array.
• For example the following declares and initializes such an array of C-strings:

char scientists[4][10] = {"Newton", "Maxwell", "Einstein", "Feynman"};

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.

You might also like