Arrays in C++

Programming often involves handling large amounts of data. Sometimes, you need to store many values of the same type — for example, a list of numbers, marks of students, or prices of products. Writing a separate variable for each value is inefficient and time-consuming.

This is where arrays come in.

An array is one of the most important and fundamental concepts in C++. It allows you to store multiple values of the same data type in a single variable. Instead of creating ten separate variables to store ten numbers, you can simply create one array that can hold all ten values.

In this post, we will explore arrays in C++ in detail — their declaration, initialization, indexing, input/output operations, multi-dimensional arrays, and much more. By the end, you will have a deep understanding of how arrays work and how to use them effectively in your programs.

What Is an Array?

An array is a collection of elements of the same type, stored in contiguous memory locations. This means all the elements are placed next to each other in memory.

Arrays make it possible to store and access multiple values efficiently using a single variable name and an index.

For example:

int numbers[5] = {10, 20, 30, 40, 50};
cout << numbers[2];

Output:

30

In this example:

  • The array numbers can hold 5 integers.
  • The elements are stored at positions 0 to 4.
  • The statement numbers[2] accesses the third element (because indexing starts from 0).

Why Use Arrays?

Let’s imagine a simple example. Suppose you need to store marks of five students. You could write:

int mark1 = 85;
int mark2 = 90;
int mark3 = 78;
int mark4 = 88;
int mark5 = 92;

This approach is not practical if the number of students is large. Instead, you can write:

int marks[5] = {85, 90, 78, 88, 92};

Now you have one variable marks that holds all five values. You can easily access, modify, or process them using loops.


Declaring an Array

To declare an array in C++, use the following syntax:

data_type array_name[array_size];

Example:

int numbers[5];

Here:

  • int is the data type.
  • numbers is the name of the array.
  • 5 is the number of elements the array can hold.

The array numbers can store five integers: numbers[0], numbers[1], numbers[2], numbers[3], and numbers[4].


Initializing an Array

You can assign values to an array either when you declare it or later in the program.

Example 1: Initialization During Declaration

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

This initializes the array with 5 values.

Example 2: Partial Initialization

int numbers[5] = {10, 20};

Here, the first two elements are set to 10 and 20, and the remaining elements are automatically set to 0.

Example 3: Automatic Size Detection

You can omit the size if you provide the values during initialization:

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

The compiler automatically determines the size (5 in this case).


Accessing Array Elements

Each element in an array is accessed using its index number. Indexing in C++ starts from 0.

So for an array of size 5:

  • The first element is at index 0.
  • The second element is at index 1.
  • The third element is at index 2.
  • The fourth element is at index 3.
  • The fifth element is at index 4.

Example:

int numbers[5] = {10, 20, 30, 40, 50};
cout << numbers[0]; // prints 10
cout << numbers[4]; // prints 50

Accessing numbers[2] gives you the value 30.


Modifying Array Elements

You can easily change the value of a specific element using its index.

int numbers[3] = {5, 10, 15};
numbers[1] = 20;
cout << numbers[1];

Output:

20

Here, the second element’s value is updated from 10 to 20.


Input and Output with Arrays

Arrays can take user input and display values just like individual variables. Usually, loops are used for efficiency.

Example: Reading and Displaying Array Elements

#include <iostream>
using namespace std;

int main() {
int numbers&#91;5];
cout &lt;&lt; "Enter 5 numbers: ";

for (int i = 0; i &lt; 5; i++) {
    cin &gt;&gt; numbers&#91;i];
}
cout &lt;&lt; "You entered: ";
for (int i = 0; i &lt; 5; i++) {
    cout &lt;&lt; numbers&#91;i] &lt;&lt; " ";
}
return 0;
}

Sample Output:

Enter 5 numbers: 1 2 3 4 5
You entered: 1 2 3 4 5

This program shows how arrays and loops work together for input and output.


Array Indexing and Memory Representation

Each element in an array is stored in a contiguous block of memory. The index represents the offset from the beginning of the array.

If numbers starts at address 1000, and each integer takes 4 bytes, then:

  • numbers[0] is at address 1000
  • numbers[1] is at address 1004
  • numbers[2] is at address 1008

C++ calculates the address of each element automatically using this formula:

Address of numbers[i] = Base address + (i * size of data type)

Example: Using Arrays in Loops

Loops are often used to process arrays.

Example 1: Calculating the Sum of Array Elements

#include <iostream>
using namespace std;

int main() {
int numbers&#91;5] = {10, 20, 30, 40, 50};
int sum = 0;
for (int i = 0; i &lt; 5; i++) {
    sum += numbers&#91;i];
}
cout &lt;&lt; "Sum = " &lt;&lt; sum;
return 0;
}

Output:

Sum = 150

Example 2: Finding the Maximum Element

#include <iostream>
using namespace std;

int main() {
int numbers&#91;5] = {12, 45, 23, 67, 34};
int max = numbers&#91;0];
for (int i = 1; i &lt; 5; i++) {
    if (numbers&#91;i] &gt; max)
        max = numbers&#91;i];
}
cout &lt;&lt; "Maximum value is: " &lt;&lt; max;
return 0;
}

Output:

Maximum value is: 67

Arrays and Functions

You can pass arrays to functions to process their elements. However, arrays are always passed by reference, meaning any changes made inside the function affect the original array.

Example:

#include <iostream>
using namespace std;

void display(int arr[], int size) {
for (int i = 0; i &lt; size; i++) {
    cout &lt;&lt; arr&#91;i] &lt;&lt; " ";
}
} int main() {
int numbers&#91;5] = {1, 2, 3, 4, 5};
display(numbers, 5);
return 0;
}

Output:

1 2 3 4 5

Example: Modifying Array in Function

#include <iostream>
using namespace std;

void doubleValues(int arr[], int size) {
for (int i = 0; i &lt; size; i++) {
    arr&#91;i] *= 2;
}
} int main() {
int nums&#91;3] = {10, 20, 30};
doubleValues(nums, 3);
for (int i = 0; i &lt; 3; i++) {
    cout &lt;&lt; nums&#91;i] &lt;&lt; " ";
}
return 0;
}

Output:

20 40 60

Arrays and Loops in Practice

Loops make working with arrays much easier. Common operations include:

  1. Reading array elements
  2. Printing array elements
  3. Calculating totals or averages
  4. Searching for a specific element
  5. Sorting the array

Example: Searching an Element in an Array

#include <iostream>
using namespace std;

int main() {
int arr&#91;5] = {2, 4, 6, 8, 10};
int key;
bool found = false;
cout &lt;&lt; "Enter element to search: ";
cin &gt;&gt; key;
for (int i = 0; i &lt; 5; i++) {
    if (arr&#91;i] == key) {
        found = true;
        cout &lt;&lt; "Element found at index " &lt;&lt; i;
        break;
    }
}
if (!found)
    cout &lt;&lt; "Element not found.";
return 0;
}

Multidimensional Arrays

An array with more than one dimension is called a multidimensional array. The most common is the two-dimensional array, often used to represent matrices or tables.


Declaring a Two-Dimensional Array

data_type array_name[rows][columns];

Example:

int matrix[2][3];

This creates a matrix with 2 rows and 3 columns.


Initializing a Two-Dimensional Array

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

Accessing Elements

You can access elements using two indices — one for row and one for column.

cout << matrix[1][2]; // prints 6

Example: Displaying a 2D Array

#include <iostream>
using namespace std;

int main() {
int matrix&#91;2]&#91;3] = {
    {1, 2, 3},
    {4, 5, 6}
};
for (int i = 0; i &lt; 2; i++) {
    for (int j = 0; j &lt; 3; j++) {
        cout &lt;&lt; matrix&#91;i]&#91;j] &lt;&lt; " ";
    }
    cout &lt;&lt; endl;
}
return 0;
}

Output:

1 2 3
4 5 6

Example: Sum of Elements in a 2D Array

#include <iostream>
using namespace std;

int main() {
int matrix&#91;2]&#91;2] = {
    {1, 2},
    {3, 4}
};
int sum = 0;
for (int i = 0; i &lt; 2; i++) {
    for (int j = 0; j &lt; 2; j++) {
        sum += matrix&#91;i]&#91;j];
    }
}
cout &lt;&lt; "Sum = " &lt;&lt; sum;
return 0;
}

Output:

Sum = 10

Character Arrays (C-Strings)

A character array stores a sequence of characters, often used to represent strings in traditional C-style.

Example:

char name[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
cout << name;

Output:

Hello

The '\0' (null character) marks the end of the string.

You can also write:

char name[] = "Hello";

Common Array Operations

  1. Traversing – Accessing each element one by one.
  2. Insertion – Adding a new element (requires shifting elements).
  3. Deletion – Removing an element (also requires shifting).
  4. Searching – Finding the position of an element.
  5. Sorting – Arranging elements in order.

Example: Sorting an Array (Ascending Order)

#include <iostream>
using namespace std;

int main() {
int arr&#91;5] = {5, 2, 8, 1, 3};
int temp;
for (int i = 0; i &lt; 5; i++) {
    for (int j = i + 1; j &lt; 5; j++) {
        if (arr&#91;i] &gt; arr&#91;j]) {
            temp = arr&#91;i];
            arr&#91;i] = arr&#91;j];
            arr&#91;j] = temp;
        }
    }
}
cout &lt;&lt; "Sorted array: ";
for (int i = 0; i &lt; 5; i++) {
    cout &lt;&lt; arr&#91;i] &lt;&lt; " ";
}
return 0;
}

Output:

Sorted array: 1 2 3 5 8

Limitations of Arrays

Although arrays are useful, they also have some limitations:

  1. Fixed size — Once declared, the size cannot be changed.
  2. No bounds checking — Accessing out-of-range indices can cause undefined behavior.
  3. Inflexibility — Insertion and deletion operations are inefficient.

These issues are later solved by data structures such as vectors, linked lists, and dynamic arrays (using pointers).


Array Bound Errors

Accessing elements outside the valid index range leads to errors or unexpected behavior.

int arr[3] = {10, 20, 30};
cout << arr[5]; // invalid access

The compiler won’t always warn you, but this can cause unpredictable results. Always ensure that your indices are within the array size.


Example: Average of Array Elements

#include <iostream>
using namespace std;

int main() {
int marks&#91;5];
int total = 0;
cout &lt;&lt; "Enter 5 marks: ";
for (int i = 0; i &lt; 5; i++) {
    cin &gt;&gt; marks&#91;i];
    total += marks&#91;i];
}
double average = total / 5.0;
cout &lt;&lt; "Average = " &lt;&lt; average;
return 0;
}

Using Constants for Array Size

Using constants makes your code cleaner and easier to modify.

const int SIZE = 5;
int arr[SIZE];

Now you can change the array size by updating only one line.


Dynamic Arrays (Overview)

Static arrays have a fixed size, but C++ also allows dynamic arrays using pointers and dynamic memory allocation.

Example using new:

int* arr = new int[5];

After using the array:

delete[] arr;

Dynamic arrays are useful when the number of elements is not known beforehand.


Arrays in Real-Life Scenarios

Arrays are widely used in programming for:

  • Storing lists of items
  • Managing student marks
  • Handling sensor readings
  • Representing matrices
  • Storing character strings
  • Building complex data structures

Key Points to Remember

  1. Arrays store multiple values of the same type.
  2. Indexing starts from 0.
  3. Array elements are stored in contiguous memory.
  4. The size of an array is fixed.
  5. Arrays work efficiently with loops.
  6. Multidimensional arrays represent tables or matrices.
  7. Character arrays are used for C-style strings.
  8. Arrays can be passed to functions by reference.
  9. Accessing out-of-bounds elements causes errors.
  10. Use dynamic arrays when flexibility is needed.

Summary

In this post, we explored arrays in C++ in depth. Here’s a quick recap:

  • Definition: Arrays store multiple values of the same data type.
  • Syntax: data_type array_name[size];
  • Initialization: Arrays can be initialized at the time of declaration.
  • Accessing: Elements are accessed using indices starting from 0.
  • Input/Output: Arrays can take user input and display output using loops.
  • 2D Arrays: Represent data in table format using rows and columns.
  • Common Operations: Traversing, searching, sorting, inserting, and deleting.
  • Limitations: Fixed size and lack of bounds checking.
  • Dynamic Arrays: Offer flexibility for variable-sized data.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *