Table of Contents
• What is an array?
• Why Do We Need Arrays?
• Types of Arrays in C++
• Declaration and Initialization of Array in C++
• Access Array Elements
• Input and Output Array Elements
Array in C++ is one of the most used data structures in C programming. It is a simple and fast way of storing
multiple values under a single name. They provide a convenient way to work with groups of related data items.
By using arrays, we can store a collection of values and access them individually.
• What is an array?
An array is a variable that can store multiple values i.e., are used to store multiple values in a single variable,
instead of declaring separate variables for each value. It can be used to store the collection of primitive data types
such as int, char, float, etc. C++ array is beneficial if we have to store similar elements. For example, if we want
to store the marks of a student in 8 subjects, then we do not need to define different variables for the marks in
different subjects. Instead, we can define an array which can store the marks in each subject at the contiguous
memory locations.
NOTE:
It is often more useful to think of an array as a collection of variables of the same type.
The elements are stored from left to right with the left-most index being at index 0 and the rightmost index being
at index (n-1) index. By using the array indexes, we can access the elements easily. The lowest address
corresponds to the first element and the highest address to the last element.
• Properties of Array
The array contains the following properties.
o Each element of an array is of same data type and carries the same size, i.e., int = 4 bytes.
o Elements of the array are stored at contiguous memory locations where the first element is stored at the
smallest memory location.
o Elements of the array can be randomly accessed since we can calculate the address of each element of the
array with the given base address and the size of the data element.
• Why Do We Need Arrays?
Arrays in C++ programming provide a structured and efficient way to work with collections of data, enabling
easier access, manipulation, and management of related values in a program. Arrays in C++ programming are
essential because they allow us to work with collections of data in a more organized and efficient way.
If we have a small number of elements, let’s say we want three variables, then we can declare them separately
like var1, var2, and var3. But if we have a large number of variables then we can use arrays to store them.
Here are several reasons why arrays are important in C++ programming:
• Storing multiple values: Arrays allow us to store multiple values of the same data type under a single
variable name. This is particularly useful when we need to work with a large set of related data items.
• Easy Access: Elements in an array can be accessed using their index or subscript value. This direct access
to elements makes it easy to retrieve and manipulate specific data without the need for separate variables
for each value.
• Efficient Data Processing: Arrays enable efficient processing of large amounts of data. This simplifies
tasks that involve processing a large dataset.
• Memory Management: Arrays provide contiguous memory allocation, which means the elements are
stored in adjacent memory locations. This sequential storage simplifies memory management.
• Efficiency: Using arrays for related data elements is more memory-efficient and often faster than using
individual variables for each element. It reduces the complexity of managing multiple variables, making
the code more readable and maintainable.
• Types of Arrays in C++
In C++ programming language, there are primarily two types of arrays:
- One-dimensional arrays / Single dimensional arrays
- Multi-dimensional arrays.
- One-dimensional arrays / Single dimensional arrays
A one-dimensional array is a collection of elements of the same data type arranged in a sequential order.
Elements in a one-dimensional array are accessed using a single index.
Syntax:
To create a one-dimensional array, we define the data type (like int, float,) and specify the name of the array
followed by square brackets [ ].
data_type array_name[array_size];
Example:
int marks[6];
Here, we declared an array marks, of int type, and its size is 6. Meaning, it can hold 6 int values only.
NOTE:
It is important to note that the size and type of an array cannot be changed once it is declared.
- Multi-dimensional arrays.
A multi-dimensional array is an array of arrays. A multi-dimensional array can be termed as an array of arrays
that stores homogeneous data in tabular form. The most common type of multi-dimensional array that is used in
the C++ language is a 2-D array. A two-dimensional array is used to store data in a table-like structure with rows
and columns. Elements in a two-dimensional array are accessed using two indices: one for the row and another
for the column.
Syntax:
To create a two-dimensional array, we define the data type (like int, float) and specify the name of the array
followed by square brackets [ ].
data_type array_name[rows_size] [columns_size];
Example:
int marks[3][3];
A one-dimensional array is like a list; A two-dimensional array is like a table.
Size of a Multidimensional Array
The size of an array is equal to the size of the data type multiplied by the total number of elements that can be
stored in an array. We can calculate the total number of elements in an array by multiplying the size of each
dimension of a multidimensional array.
For example:
int marks[2][4];
• The array int marks[2][4] can store total (2*4) = 8 elements.
• In C++ int data type takes 4 bytes and we have 8 elements in the array ‘marks’ of the int type.
• Total size = 4*8 = 32 bytes.
We can think of this array as a table with 2 rows and each row has 4 columns as shown below.
• Declaration of Array in C++
In C++, we can declare an array by simply specifying the data type first and then the name of the array with its
size.
Syntax:
data_type array_name[array_size];
Example:
int age[5];
• Initialization of Array in C++
Array initialization is the process of assigning/storing elements to an array. The initialization can be done in a
single statement or one by one. In C++, we can initialize an array in two ways:
i. Initializing the array during the declaration
ii. Assigning the value after the declaration
i. Initializing the array during the declaration
We can initialize an array while declaring it by assigning elements to the array during the declaration using
curly braces around the elements separated by commas.
❖ Initialize Array with Values in C++
The values enclosed in curly braces ‘{}’ are assigned to the array. For example,
int x[6] = {19, 10, 8, 17, 9, 15};
❖ Initialize Array with Values and without Size in C++
We have initialized the array with values but we have not declared the length of the array, therefore, the
length of an array is equal to the number of elements inside curly braces. For example,
int x[ ] = {19, 10, 8, 17, 9, 15};
❖ Initialize Array with Empty Members (partially) in C++
In C++, if an array has a size n, we can store up to n number of elements in the array. However, what
will happen if we store less than n number of elements. For example,
int x[6] = {19, 10, 8};
In such cases, the compiler assigns random values to the remaining places. Often, this random value is
simply 0.
ii. Assigning the value after the declaration
After the declaration of the array, we can assign elements to the array at each index.
❖ Initialize Array after Declaration (Using Loops)
This method is generally used when we want to take input from the user or we cant to assign elements
one by one to each index of the array. We can modify the loop conditions or change the initialization
values according to requirements. For example,
for (int i = 0; i < n; i++) {
marks[i] = value;
}
❖ Initialize the array with zero in C++
We can initialize the array with all elements as ‘0’ by specifying ‘0’ inside the curly braces. This will
happen in case of zero only. If we try to initialize the array with a different value say ‘2’ using this
method then ‘2’ is stored at the 0th index only. For example,
int marks[6] = {0};
• Inserting Elements in an Array
Array can be filled by two way,
• Direct assignment
In this, we directly assign value to the array element.
Syntax:
array_name[index-1] = value;
e.g. marks[0] = 5;
marks[1] = 2;
marks[2] = 9;
marks[3] = 1;
• Reading from user
In this type, we need to use loops and cout function in order to insert user specified values..
cin>> array_name[index - 1];
e.g. for(i = 0; i <= 5; i++)
{
cout<<"Enter marks ";
cin>> marks[i]; // reading data from user
}
Example:
#include <iostream>
using namespace std;
int main()
{
int numbers[5];
cout << "Enter 5 numbers to store into the array: " << endl;
// store input from user to array
for (int i = 0; i < 5; ++i) {
cin >> numbers[i];
}
return 0;
}
• Accessing Array Elements in C++
Elements of an array can be accessed by specifying the name of the array, then the index of the element enclosed
in the array subscript operator []. For example, marks[i].
1. Using a for loop
Example:
#include <iostream>
using namespace std;
int main()
{
int age[7] = {19, 18, 21, 20, 17, 29, 34 };
int i;
for(i = 0; i < 7; i++){
cout << "Element at index " << i <<" is " << age[i]<<endl;
}
return 0;
}
Sample Output:
Element at index 0 is 19
Element at index 1 is 18
Element at index 2 is 21
Element at index 3 is 20
Element at index 4 is 17
Element at index 5 is 29
Element at index 6 is 34
Example 1:
#include<iostream>
using namespace std;
int main()
{
int i, n, num[20], sum=0;
cout<<"How many numbers you want to enter ? (max. 20) ";
cin>>n;
cout<<"Enter "<<n<<" numbers: "<<endl;
for(i=0; i<n; i++)
{
cin>>num[i];
sum += num[i];
}
cout<<"\nThe sum of all "<<n<<" numbers is "<<sum<<endl;
return 0;
}
Sample Output:
The sum of all ___ numbers is ___
2. Using a while loop
Example:
#include<iostream>
using namespace std;
int main()
{
int n, i=0, num[20], sum=0;
cout<<"How many numbers you want to enter ? ";
cin>>n;
cout<<"Enter "<<n<<" numbers: "<<endl;
while(i<n)
{
cin>>num[i];
sum += num[i];
i++;
}
cout<<"\nThe sum of all "<<n<<" numbers is "<<sum<<endl;
return 0;
}
Sample Output:
The sum of all ___ numbers is ___
3. Using Function
Example
#include<iostream>
using namespace std;
int findSum(int [], int);
int main()
{
int n, i, arr[50], sum;
cout<<"How many numbers you want to enter ? (max. 50): "<<endl;
cin>>n;
cout<<"Enter "<<n<<" numbers: "<<endl;
for(i=0; i<n; i++)
cin>>arr[i];
sum = findSum(arr, n);
cout<<"\nThe sum of all "<<n<<" numbers is "<<sum<<endl;
return 0;
}
int findSum(int arr[], int n)
{
int i, sum=0;
for(i=0; i<n; i++)
sum = sum+arr[i];
return sum;
}
Sample Output:
The sum of all ___ numbers is ___
Two Dimensional Array (or 2D Array)
A two-dimensional array in C++ is a collection of elements organized in rows and columns. It can be visualized
as a table or a grid, where each element is accessed using two indices: one for the row and one for the column.
Like a one-dimensional array, two-dimensional array indices also range from 0 to n-1 for both rows and columns.
A two-dimensional array is also called a matrix because it contains a matrix structure. It consists of a number of
Rows and Columns. Each data value is stored in matrix format according to the sequence of the data values
specified. It can be of any type like integer, character, float, etc. depending on the initialization.
Thus, every element in array Arr is identified by an element name of the form Arr[ i ][ j ], where Arr is the name
of the array, and i and j are the subscripts that uniquely identify each element in Arr.
Why do we need a 2D Array?
Often, data comes naturally in the form of a table or in rows and columns structure. Example, spreadsheet data,
the periodic table, multiplication table, Employee and their salaries, school results etc. Such data needs to be
stored in more than one dimension. Hence, we use Two-Dimensional Arrays in order to store the data efficiently.
A Two Dimensional Array also makes it very easy to access every element in the array.
Syntax of Two-Dimensional Array in C++
A two-dimensional array can be defined as an array of arrays. A mathematical matrix can be visualized as a two-
dimensional array. The syntax of the two-dimensional arrays in C++ is straightforward.
data_type array_name [row_size][column_size];
Example:
int test[2][3]
The data inside the two-dimensional array in C++ can be visualized as a table (row-column manner).
Initializing a 2D array in C++
In order to understand how to initialize a Two Dimensional array with data values, we follow the following three
syntax. There are three ways to initialize a 2D array:
• Using Initializer List
• Using Loops
• Using Zero
1. Using the Initializer list
We can initialize a 2D array using an initializer list in two ways. Below is the first method of initializing a 2D
array using an initializer list.
First Method: The below array has 2 rows and 4 columns. The elements are filled in a way that
the first 4 elements are filled in the first row and the next 4 elements are filled in the second row.
Here, the values are stored in the array from left to right. i.e. first 4 elements will be stored in
Row 1, the next four in row 2, and so on.
int arr[2][4] = {0, 1, 2, 3, 4, 5, 6, 7};
OR
Here, the values are stored in the array from left to right. i.e. first 2 elements will be stored in row
1, the next two in row 2, and the next two in row 3.
int arr[3][2] = {100, 10, 200, 20, 300, 30} ;
Second Method: The below way is the cleaner way to initialize a 2D array the nested list represents the elements
in a row and the number of elements inside it is equal to the number of columns in a 2D array.
The number of nested lists represents the number of columns.
int arr[2][4] = {{0, 1, 2, 3}, {4, 5, 6, 7}};
OR
Here every set of braces represents a row. Each nested braces value will be stored in separate
rows. In the below example, there are 3 inner braces, so there will be 3 rows in the Two-
dimensional Array.
int arr[3][2] = {{100, 10}, {200, 20}, {300, 30}} ;
This method can also used this way;
int arr[3][2] =
{
{100, 10},
{200, 20},
{300, 30}
};
2. Using Loops
To initialize 2D array we have to use two nested loops and nested loops are equal to the dimension. For example,
to initialize a 3D array we have to use three nested loops.
Example: In the below example we have initializes the 2D array with 1. The outer loop is used to track rows
“i=0” means the first row because of 0 indexing similarly “j=0” means the first column and combining
this arr [0][0] represents the first cell of the 2D array.
int arr[2][4];
for(int i = 0; i < 2; i++){ // Outer for loop for traversing rows
for(int j = 0; j < 4; j++){ // Inner for loop for traversing columns
arr[i][j] = 1;
}
}
3. Using Zero
In C++, we can initialize the two-dimensional array with a zero in a single statement.
Syntax
arr[2][4] = {0};
Here, all the elements will be initialized with the value zero.
Accessing Elements of Two-Dimensional Arrays in C++
Just like the Indexing method used for accessing elements of a One-Dimensional Array, Two-Dimensional Arrays
also use the Indexing method. The only difference is that the row and column indexes are used to access array
elements.
We can access the elements of a Two-dimensional array using row and column indices. It is similar to matrix
element position but the only difference is that here indexing starts from 0.
Syntax:
array_name [row_index][column_index];
array_name[i][j];
where,
• i: Index of row.
• j: Index of the column.
Example: int arr[4][3]={{10,20,30},{40,50,60},{70,80,90},{100,110,120}};
Suppose, in this example, we want to access element 80. It will be: arr[2][1];
Note: indexing always starts with zero.
Printing the Elements in a Two-Dimensional Array in C++
Printing elements of a two-dimensional array can be done using two for loops.
Example:
int arr[4][3];
for(int i = 0; i < 4; i++){ // Outer for loop for traversing rows
for(int j = 0; j < 3; j++){ // Inner for loop for traversing columns
cout << arr[i][j] << " "; // Print individual array element
}
}
Example:
To print a single array element from a 2D Array
#include<iostream>
using namespace std;
int main()
{
int arr[4][2] = { { 10, 11 }, { 20, 21 }, { 30, 31 }, { 40, 41 } };
int val = arr[2][1] ;
cout << val ;
}
Sample Output:
31
Example 2:
To print all the elements of a 2D Array
#include<iostream>
using namespace std;
int main()
{
int arr[4][2] = { { 10, 11 }, { 20, 21 }, { 30, 31 }, { 40, 41 } };
cout << "The elements of 2D Array are : "<<endl ;
for (int x = 0; x < 4 ; x++) // Outer for loop for traversing rows
{
for(int y = 0; y < 2 ; y++) // Inner for loop for traversing columns
{
cout <<"\t" << arr[x][y] ; // Print individual array element
}
cout << endl;
}
}
Sample Output:
Elements of 2D Array are :
10 11
20 21
30 31
40 41
Taking 2D Array Elements as User Input in C++
Previously, we saw how we can initialize a 2D array with pre-defined values. But we can also make it a user input
too.
Example:
#include<iostream>
using namespace std;
int main( )
{
int arr[2][2];
int i, j;
cout<<"Enter the elements in a [2X2] 2-D Array: "<<endl;
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<"\n arr["<<i<<"]["<<j<<"]= ";
cin>>arr[i][j];
}
}
cout<<"\nThe [2X2] 2-D Array is:\n";
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
cout<<"\t"<<arr[i][j];
}
cout<<endl;
}
}
Sample Output:
Enter the elements in a [2X2] 2-D Array:
arr[0][0]= 1
arr[0][1]= 2
arr[1][0]= 3
arr[1][1]= 4
The [2X2] 2-D Array is:
1 2
3 4
Passing a 2D Array Parameter to Functions in C++
In C++, arrays are always passed as pointers. The same goes for the two-dimensional arrays. There exist two
common ways or methods of passing a 2D array to functions in C++.
Method 1: Passing 2D Array with Rows and Columns
Syntax
return_type name (array_ return_type array_name[rows][coloumns], int rows, int col){
// Body of the array
}
Example:
#include <iostream>
using namespace std;
void printArr(int arr[3][2], int n, int m)
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main()
{
const int n = 3, m = 2;
int arr[n][m] = { { 10, 15 }, { 20, 25 }, { 30, 35 } };
printArr(arr, n, m);
return 0;
}
Sample Output:
10 15
20 25
30 35
Method 2: Passing 2D Array with Rows and Columns Declared Globally.
Syntax:
return_type name (array_ return_type array_name[rows][coloumns],
Example
#include <iostream>
using namespace std;
// declaring global no of rows and cols
const int n = 3, m = 2;
void printArr(int arr[n][m])
{
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main()
{
int arr[n][m] = { { 10, 15 }, { 20, 25 }, { 30, 35 } };
// calling print function
printArr(arr);
return 0;
}
Sample Output:
10 15
20 25
30 35