×
>
<

C++ Programming

C++ Arrays | CrackEase

Arrays in C++

Arrays in C++ Introduction

Array 

An array in C++ is a collection of elements of the same data type stored at contiguous memory locations. Arrays allow you to store multiple values under a single variable name and access each element using an index.

Instead of declaring separate variables like int a, b, c, d, e;, you can group them into a single array int arr[5]; which allocates five contiguous memory locations accessible via indices 0 to 4.

Note: Array indices in C++ always start at 0. An array of size n has valid indices from 0 to n-1.

C++ Arrays
Array Memory Layout

Key Properties of Arrays:-

  • Zero-Based Indexing: Array indices start at 0 and go up to n-1 for an array of size n.
  • Homogeneous Elements: All elements must be of the same data type.
  • Contiguous Memory: Elements are stored in consecutive memory locations.
  • Fixed Size: Array size is determined at compile time and cannot be changed.
  • Random Access: Any element can be accessed directly using its index in O(1) time.
Ways to Define an Array

Method 1: Specifying Size Only

Declare an array by specifying only the size. Elements contain garbage values until initialized.

  
int arr[5];  // declares array of 5 integers (uninitialized)
  

Method 2: Initialization Without Size

Let the compiler infer the size from the initializer list.

  
int arr[] = {10, 20, 30, 40, 50};  // size automatically set to 5
  

Method 3: Specifying Size and Initializing

Explicitly specify both size and initial values.

  
int arr[5] = {10, 20, 30, 40, 50};
  

Method 4: Partial Initialization

Initialize some elements; remaining elements are zero-initialized.

  
int arr[5] = {10, 20};  // arr[2], arr[3], arr[4] are set to 0
  

Method 5: Zero Initialization

Initialize all elements to zero.

  
int arr[5] = {0};  // all 5 elements set to 0
  

Using std::vector (Recommended for Dynamic Size)

For variable-length arrays, use std::vector which is part of the C++ Standard Library.

  
#include <vector>

std::vector<int> arr(n);  // dynamic array of size n
  
Array Access Methods
Array Indexing

1. Using Index Notation:

Access elements using square brackets with the index. For example, arr[2] accesses the third element. This is the most common method.

2. Using Pointer Arithmetic:

Since arrays are stored contiguously, you can use pointer arithmetic. The expression *(arr + i) is equivalent to arr[i].

3. Using Range-Based For Loop (C++11):

Modern C++ provides range-based for loops: for (int x : arr) iterates through all elements without explicit indexing.

C++ Array Example

Example - Declaring and Traversing an Array:

  
#include <iostream>
using namespace std;

int main()
{
    int arr[5] = {6, 9, 1, 5, 3};
    
    cout << "Array elements are:" << endl;
    
    for (int i = 0; i < 5; i++)
    {
        cout << "arr[" << i << "] = " << arr[i] << endl;
    }
    
    return 0;
}
  

Output:

  
Array elements are:
arr[0] = 6
arr[1] = 9
arr[2] = 1
arr[3] = 5
arr[4] = 3
  
Array Memory Layout

Array elements occupy sequential memory locations. Each element's address differs by the size of the data type (e.g., 4 bytes for int on most systems).

Example - Displaying Memory Addresses:

  
#include <iostream>
using namespace std;

int main()
{
    int arr[5] = {6, 9, 1, 5, 3};
    
    cout << "Element addresses:" << endl;
    
    for (int i = 0; i < 5; i++)
    {
        cout << "arr[" << i << "] at " << &arr[i] 
             << " = " << arr[i] << endl;
    }
    
    return 0;
}
  

Sample Output (addresses vary per run):

  
Element addresses:
arr[0] at 0x7ffd8b2a2f40 = 6
arr[1] at 0x7ffd8b2a2f44 = 9
arr[2] at 0x7ffd8b2a2f48 = 1
arr[3] at 0x7ffd8b2a2f4c = 5
arr[4] at 0x7ffd8b2a2f50 = 3
  

Observation: Each address increases by 4 bytes (size of int), demonstrating contiguous memory allocation.

Practical Example - Finding Element Frequency

Example - Count Frequency of an Element:

  
#include <iostream>
#include <vector>
using namespace std;

int main()
{
    int n;
    cout << "Enter number of elements: ";
    cin >> n;
    
    vector<int> arr(n);
    
    cout << "Enter " << n << " elements: ";
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    
    int key, count = 0;
    cout << "Enter element to find frequency: ";
    cin >> key;
    
    for (int i = 0; i < n; i++)
    {
        if (arr[i] == key)
        {
            count++;
        }
    }
    
    cout << "Frequency of " << key << " is " << count << endl;
    
    return 0;
}
  

Sample Output:

  
Enter number of elements: 6
Enter 6 elements: 2 3 4 4 5 6
Enter element to find frequency: 4
Frequency of 4 is 2
  
Advantages and Disadvantages
Advantages Disadvantages
Fast random access O(1) Fixed size at compile time
Efficient memory usage No bounds checking
Cache-friendly (contiguous) Insertion/deletion is expensive
Simple syntax May waste memory if oversized

Tip: Use std::vector when you need dynamic resizing, or std::array for a safer fixed-size alternative with bounds checking.

Important Array Rules

Valid and Invalid Operations:

  
int arr[5];

arr[0];   // Valid - first element
arr[4];   // Valid - last element
arr[-1];  // Invalid - negative index
arr[5];   // Invalid - out of bounds (undefined behavior)

int arr[];  // Invalid - size required without initializer
  

Partial and Zero Initialization:

  
int arr[5] = {1, 2, 3};  // arr[3] and arr[4] are 0
int arr[5] = {0};        // all elements are 0
int arr[5] = {};         // all elements are 0 (C++11)
  
Multi-Dimensional Arrays
2D Array

Two-Dimensional Arrays:

A 2-D array stores elements in rows and columns, like a matrix. Declared as int arr[rows][cols]; where valid indices are arr[0..rows-1][0..cols-1].

Accessing 2-D Elements:

Use two indices: arr[row][col]. For example, arr[2][1] accesses the element at row 2, column 1.

Memory Layout:

2-D arrays are stored in row-major order - all elements of row 0 first, then row 1, and so on.

2-D Array Example

Example - Declaring and Traversing a 2-D Array:

  
#include <iostream>
using namespace std;

int main()
{
    // 5 rows and 2 columns
    int arr[5][2] = {
        {0, 0},
        {1, 2},
        {2, 4},
        {3, 6},
        {4, 8}
    };
    
    cout << "2-D Array elements:" << endl;
    
    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 2; j++)
        {
            cout << "arr[" << i << "][" << j << "] = " 
                 << arr[i][j] << endl;
        }
    }
    
    return 0;
}
  

Output:

  
2-D Array elements:
arr[0][0] = 0
arr[0][1] = 0
arr[1][0] = 1
arr[1][1] = 2
arr[2][0] = 2
arr[2][1] = 4
arr[3][0] = 3
arr[3][1] = 6
arr[4][0] = 4
arr[4][1] = 8
  
2-D Array Initialization Methods

Method 1: Row-wise Initialization (Recommended):

  
int arr[3][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
};
  

Method 2: Single Line Initialization:

  
int arr[3][4] = {1,2,3,4, 5,6,7,8, 9,10,11,12};
  

Method 3: Partial Initialization:

  
int arr[3][4] = {
    {1, 2},       // arr[0][2], arr[0][3] are 0
    {5}           // arr[1][1], arr[1][2], arr[1][3] are 0
};                // arr[2][0..3] are all 0
  
Footer Content | CrackEase