Arrays In C++

An array in C++ is a collection of elements of the same data type stored in contiguous memory locations. It provides a way to store multiple values of the same data type under a single name. Each element in the array is accessed by its index, which represents its position within the array.

Need for Arrays in C++

Arrays are essential in C++ programming for several reasons:

  1. Storage Efficiency: Arrays allow efficient storage of multiple values of the same data type in contiguous memory locations. This enables optimized memory usage compared to individual variables.
  2. Access and Manipulation: Arrays provide a convenient way to access and manipulate a group of related elements using a single identifier and index notation. This simplifies code readability and organization.
  3. Iteration and Processing: Arrays facilitate iteration over a sequence of elements using loops such as for or while. This makes it easier to perform repetitive operations on collections of data.
  4. Data Organization: Arrays are useful for organizing and managing data in structured formats, such as lists, matrices, tables, or databases. They allow for easy representation and manipulation of multidimensional data structures.
  5. Passing to Functions: Arrays can be passed as arguments to functions, enabling modular and reusable code. Functions can operate on array elements without needing to know the exact size or contents of the array.
  6. Efficient Memory Access: Accessing elements of an array by index allows for efficient random access, as the memory locations are contiguous. This results in faster read and write operations compared to non-contiguous data structures.

One Dimensional Array in C++

A one-dimensional array in C++ is a collection of elements of the same data type arranged sequentially in memory. It allows for efficient storage and manipulation of a fixed-size sequence of elements.

Declaration/Initialization of One-Dimensional Array

Declaration of One-Dimensional Array

To declare a one-dimensional array in C++, you use the following syntax:

dataType arrayName[arraySize];

Where:

  • dataType specifies the type of data that the array will hold (e.g., int, float, char, etc.).
  • arrayName is the identifier or name given to the array.
  • arraySize represents the number of elements that the array can store.

For example, if you want to declare an array named numbers of size 5 to hold integers, you would write:

int numbers[5];

This statement declares an array named numbers that can store 5 integer values.

Initialization of One-Dimensional Array

After declaring an array, you can initialize its elements at the time of declaration using braces . There are several ways to initialize the array:

Initializing with Values:

You can provide a list of initial values enclosed in braces at the time of declaration. The number of values provided must match the size of the array. For example:

int numbers[5] = {1, 2, 3, 4, 5};

This initializes the numbers array with values 1, 2, 3, 4, and 5 at indices 0 to 4 respectively.

Partial Initialization:

You can partially initialize the array, leaving some elements uninitialized. In this case, the remaining elements are automatically initialized to zero. For example:

int numbers[5] = {1, 2}; // Initializes first two elements to 1 and 2, rest to 0

This initializes the numbers array with values 1 and 2 at indices 0 and 1 respectively, and sets the remaining elements at indices 2 to 4 to 0.

Initializing without Specifying Size:

If you don't specify the size of the array, the compiler can infer it from the number of initial values provided. For example:

int numbers[] = {1, 2, 3, 4, 5}; // Compiler infers the size as 5

Inputting Array Elements

You can input elements into an array using a loop or individually assign values to each element of the array.

Example (Input without using Loop):

#include <iostream>
using namespace std;
 
int main() {
    // Declaration/Initialization of an array of integers
    int numbers[5];
 
    // Individually assigning values to array elements
    cout << "Enter 5 numbers:" << endl;
    cin >> numbers[0];
    cin >> numbers[1];
    cin >> numbers[2];
    cin >> numbers[3];
    cin >> numbers[4];
 
    return 0;
}
  • An array named numbers of size 5 is declared.
  • The program prompts the user to enter 5 numbers.
  • The cin statements individually input values into each element of the numbers array.
  • The user input is stored in the respective elements of the array.

Example (Input using Loop):

#include <iostream>
using namespace std;
 
int main() {
    // Declaration of an array of integers
    int numbers[5];
 
    // Inputting array elements using a loop
    cout << "Enter 5 numbers:" << endl;
    for (int i = 0; i < 5; ++i) {
        cin >> numbers[i];
    }
 
    return 0;
}
  • This program prompts the user to input 5 numbers.
  • Each number input by the user is stored in the respective element of the numbers array.

Accessing and Printing Array Elements

Array elements can be accessed using their index within square brackets []. Array indexing starts from 0 for the first element and goes up to arraySize - 1.

Example (Accessing Array Elements):

#include <iostream>
using namespace std;
 
int main() {
    // Declaration/Initialization of an array of integers
    int numbers[5] = {10, 20, 30, 40, 50};
 
    // Accessing and printing array elements
    cout << "Array elements:" << endl;
    for (int i = 0; i < 5; ++i) {
        cout << "Element " << i << ": " << numbers[i] << endl;
    }
 
    return 0;
}

Output:

Array elements:
Element 0: 10
Element 1: 20
Element 2: 30
Element 3: 40
Element 4: 50

Explanation:

  • The program declares and initializes an array numbers with the values {10, 20, 30, 40, 50}.
  • It then prints each element of the array along with its index using a loop.
  • The loop iterates from 0 to 4 (inclusive), accessing each element of the array using its index.
  • The output displays each array element along with its corresponding index.

Passing One-dimensional Array to a Function

#include <iostream>
using namespace std;
 
// Function to print elements of a 1D array
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}
 
int main() {
    int arr[5] = {1, 2, 3, 4, 5};
 
    // Calling the function
    printArray(arr, 5);
 
    return 0;
}

Output:

1 2 3 4 5

Here,

  • The array arr is declared and initialized with five integer values: {1, 2, 3, 4, 5}.
  • The printArray() function is called with two arguments: the array arr and the size of the array, which is 5.
  • Inside the printArray() function, a for loop iterates through each element of the array arr.
  • During each iteration of the loop, the value of the current element of the array is printed followed by a space.
  • After printing all the elements of the array, the loop terminates, and the function execution completes.

Program to Find Sum of Array Elements

#include <iostream>
using namespace std;
 
int main() {
    // Define an array
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array
    int sum = 0; // Initialize sum variable
 
    // Iterate through the array and add each element to the sum
    for (int i = 0; i < size; ++i) {
        sum += arr[i];
    }
 
    // Print the sum
    cout << "Sum of array elements - " << sum << endl;
 
    return 0;
}

Output:

Sum of array elements - 15

Explanation:

This program first defines an array arr with some integer values. It then calculates the size of the array using the formula sizeof(arr) / sizeof(arr[0]), where sizeof(arr) gives the total size of the array in bytes, and sizeof(arr[0]) gives the size of one element in the array. Dividing the total size by the size of one element gives the number of elements in the array.

Next, it iterates through the array using a for loop and adds each element to the sum variable. Finally, it prints the sum of the array elements to the console.

Two-Dimensional Array in C++

A two-dimensional array in C++ is a collection of elements arranged in rows and columns. It can be visualized as a grid or matrix where each element is identified by its row and column index.

Declaration/Initialization of a Two-Dimensional Array

In C++, you can declare and initialize a two-dimensional array using the following syntax:

dataType arrayName[rows][cols] = {
    {element11, element12, ..., element1cols},
    {element21, element22, ..., element2cols},
    ...
    {elementrows1, elementrows2, ..., elementrowscols}
}

Where:

  • dataType specifies the type of data stored in the array (e.g., int, float, char, etc.).
  • arrayName is the identifier used to access the array.
  • rows and cols represent the number of rows and columns in the array, respectively.
  • {element11, element12, ..., element1cols} to {elementrows1, elementrows2, ..., elementrowscols} are initial values for each element of the array.

Example:

#include <iostream>
using namespace std;
 
int main() {
    // Declaration and Initialization of a 2D array of integers
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
 
    return 0;
}

In this example, a two-dimensional array named matrix of size 3x3 is declared and initialized with the values.

Inputting Array Elements

You can input elements into a two-dimensional array using nested loops or individually assign values to each element of the array.

Example (Input without using Nested Loop):

#include <iostream>
using namespace std;
 
int main() {
    // Declaration of a 2D array of integers
    int matrix[3][3];
 
    // Inputting array elements without using a nested loop
    cout << "Enter 3x3 matrix elements:" << endl;
    cout << "Enter matrix[0][0]: ";
    cin >> matrix[0][0];
    cout << "Enter matrix[0][1]: ";
    cin >> matrix[0][1];
    cout << "Enter matrix[0][2]: ";
    cin >> matrix[0][2];
    cout << "Enter matrix[1][0]: ";
    cin >> matrix[1][0];
    cout << "Enter matrix[1][1]: ";
    cin >> matrix[1][1];
    cout << "Enter matrix[1][2]: ";
    cin >> matrix[1][2];
    cout << "Enter matrix[2][0]: ";
    cin >> matrix[2][0];
    cout << "Enter matrix[2][1]: ";
    cin >> matrix[2][1];
    cout << "Enter matrix[2][2]: ";
    cin >> matrix[2][2];
 
    return 0;
}
  • This program prompts the user to input elements for a 3x3 matrix.
  • Each element input by the user is directly stored in the respective position of the matrix array without using a nested loop.
  • The program explicitly prompts the user to enter each element separately and then reads the input using cin.

Example (Input using Nested Loop):

#include <iostream>
using namespace std;
 
int main() {
    // Declaration of a 2D array of integers
    int matrix[3][3];
 
    // Inputting array elements using nested loop
    cout << "Enter 3x3 matrix elements:" << endl;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            cin >> matrix[i][j];
        }
    }
 
    return 0;
}
  • This program prompts the user to input elements for a 3x3 matrix.
  • Each element input by the user is stored in the respective position of the matrix array.

Accessing Array Elements

Array elements in a two-dimensional array can be accessed using two indices representing row and column.

Example (Accessing Array Elements):

#include <iostream>
using namespace std;
 
int main() {
    // Declaration and Initialization of a 2D array of integers
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
 
    // Accessing and printing array elements
    cout << "Array elements:" << endl;
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }
 
    return 0;
}

Output:

Array elements:
1 2 3 
4 5 6 
7 8 9 
  • The program declares and initializes a 3x3 array named matrix with the assigned values.
  • The outer loop iterates over each row of the array (i represents the row index).
  • The inner loop iterates over each column of the array within the current row (j represents the column index).
  • Inside the inner loop, each element of the array is accessed using its row and column indices (matrix[i][j]) and printed to the console.
  • After printing all the elements in a row, a newline character (endl) is used to move to the next line for the next row.
  • This process repeats for each row and column, printing all elements of the array in a 3x3 grid format.

Passing Two-dimensional Array to a Function

#include <iostream>
using namespace std;
 
// Function to print elements of a 2D array
void printArray(int arr[3][3], int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}
 
int main() {
    int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
 
    // Calling the function
    printArray(arr, 2, 3);
 
    return 0;
}

Output:

1 2 3 
4 5 6 

Explanation:

  • The 2D array arr is declared and initialized with two rows and three columns.
  • The printArray() function is called with three arguments: the 2D array arr, the number of rows (2), and the number of columns (3).
  • Inside the printArray() function, a nested loop iterates through each element of the 2D array.
  • During each iteration of the nested loop, the value of the current element of the array is printed followed by a space.
  • After printing all the elements of the array, the inner loop terminates, and a newline is printed to move to the next row.
  • This process continues until all elements of the 2D array are printed.

Differences Between 1D and 2D Arrays

Aspect1D Array2D Array
DimensionSingle-dimensionalTwo-dimensional
DeclarationDeclared using a single set of square brackets [ ]Declared using two sets of square brackets [ ][ ]
AccessAccessed using a single indexAccessed using two indices (row and column)
Memory AllocationContiguous block of memoryContiguous blocks of memory arranged in rows and columns
UsageSuitable for linear data representationSuitable for representing tabular data, matrices, etc.

Advantages And Disadvantage of Arrays

Advantages

  • Efficient Data Storage: Arrays provide an efficient way to store a collection of elements of the same data type in contiguous memory locations.
  • Random Access: Elements in an array can be accessed randomly by their index, allowing for quick retrieval or modification of elements at any position within the array.
  • Simple Syntax: Arrays have a simple and straightforward syntax for declaration and usage, making them easy to understand and implement in code.
  • Compact Code: Using arrays can lead to more compact and concise code, especially when dealing with repetitive tasks or operations on multiple elements.
  • Iterative Operations: Arrays are well-suited for iterative operations such as traversing, searching, and sorting, making them versatile for various algorithms and data manipulation tasks.

Disadvantages

  • Fixed Size: Arrays have a fixed size, set at the time of declaration, which cannot be changed dynamically. This can lead to inefficiencies in memory usage.
  • Static Memory Allocation: Arrays allocate memory statically, leading to potential memory wastage or insufficiency if the array size is not optimized.
  • Sequential Storage: Elements in an array are stored sequentially in memory, which can result in slower performance for certain operations like insertion or deletion of elements.
  • Homogeneous Data Types: Arrays can only store elements of the same data type, limiting their flexibility for storing heterogeneous data or complex structures.
  • No Built-in Bounds Checking: Most programming languages do not provide built-in bounds checking for array accesses, which can lead to runtime errors or undefined behavior if accessing elements outside the array bounds.
How's article quality?

Last updated on -

Page Contents