Loading...
C++ Arrays

C++ Arrays

In this tutorial, we will learn to work with arrays. We will learn to declare, initialize, and access array elements in C++ programming with the help of examples, and advantages and disadvantages of array.


Array

  • In C++, an array is a variable that can store multiple values of the same type.
  • An array is a collection of items stored at contiguous memory locations.
  • Elements can be accessed randomly using indices of an array.
  • They can be used to store collection of primite data types such as int, float, double, char, etc of any particular type.

Properties of Array

The array contains the following properties:

  • Each element of an array is of same data type and carries the same size, i.e., int = 2 bytes.
  • Elements of the array are stored at contiguous memory locations where the first element is stored at the smallest memory location.
  • 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.

For example,

Suppose a class has 20 students, and we need to store the grades of all of them. Instead of creating 20 separate variables, we can simply create an array:

double section[20];

Here, section is an array that can hold a maximum of 20 elements of double type.

In C++, the size and type of arrays cannot be changed after its declaration.


Array Declaration

There are various ways in which we can declare an array.

It can be done by specifying its type and size, by initializing it or both.

Rules for declaring a single-dimentional array

  • Type : The type is the type of elements to be stored in the array, and it must be a valid C++ data type.
  • Array-Name : The array-Name is the name to be assigned to the array.
  • Array-Size : The array-Size is the number of elements to be stored in the array. It must be an integer and greater than 0.

Syntax

data_type arrayName[array_Size];

For example,

int marks[2];

Here,

  • int - type of element to be stored
  • marks - name of the array
  • 2 - size of the array

Access Elements in an Array

  • In C++, each element in an array is associated with a number.
  • The number is known as an array index.
  • We can access elements of an array by using those indices.
// syntax to access array elements
array[index];

Consider the array marks we have seen above.

C++ Array Declaration
Elements of an array in C++

Few Things to Remember:

  • The array indices start with 0. Meaning marks[0] is the first element stored at index 0.
  • If the size of an array is n, the last element is stored at index (n-1). In this example, marks[5] is the last element.
  • Elements of an array have consecutive addresses.
  • For example, suppose the starting address of marks[0] is 2120d. Then, the address of the next element marks[1] will be 2124d, the address of marks[2] will be 2128d and so on.

Here, the size of each element is increased by 4. This is because the size of int is 4 bytes.


Array Initialization

  • It is the process of assigning/storing elements to an array.
  • The Initialization can be done in a single Statement or one by one.
  • Note : The first element in an array is stored at index 0, while the last element is stored at index n-1, where n is the total number of elements in the array.

In C++, it's possible to initialize an array during declaration.
For example,

// declare and initialize and array
int marks[6] = {10, 12, 6, 11, 5, 4};

Another method to initialize array during declaration:

// declare and initialize and array
int marks[] = {10, 12, 6, 11, 5, 4};

Here, we have not mentioned the size of the array. In such cases, the compiler automatically computes the size.


Array With Empty Members

In C++, if an array has a size n, we can store upto n number of elements in the array. However, what will happen if we store less than n number of elements.

For example,

// store only 2 elements in the array
int marks[4] = {12, 14};

Here, the array marks has a size of 4. However, we have initialized it with only 2 elements.

In such cases, the compiler assigns random values to the remaining places. Oftentimes, this random value is simply 0.


How to insert and print array elements?

int age[6] = {12, 14, 6, 11, 19}
                      
// change 3th element to 7
mark[2] = 7;
                      
// take input from the user and store the value at forth position
cin >> age[3];
                                  
// take input from the user and insert at n'th position
cin >> age[n-1];
                      
// print first element of the array
cout << age[0];
                      
// print n'th element of the array
cout >> age[n-1];

Example 1: Print The Elements of an Array

#include <iostream>
using namespace std;

int main() {
    int age[5] = {6, 4, 8, 15, 25};
                                      
    cout << "The age are: ";
                                      
    //  Printing array elements using range based for loop
    for (const int &n : age) {
        cout << n << "  ";
    }                       
    cout << "\nThe age are: ";
                                      
    //  Printing array elements using traditional for loop
    for (int i = 0; i < 5; ++i) {
        cout << age[i] << "  ";
    }
                                      
    return 0;
}

Output

The age are: 6  4  8  15  25
The age are: 6  4  8  15  25

Here, we have used a for loop to iterate from i = 0 to i = 4.
In each iteration, we have printed numbers[i].

We again used a range based for loop to print out the elements of the array. To learn more about this loop, check C++ Ranged for Loop.

Note: In our range based loop, we have used the code const int &n instead of int n as the range declaration. However, the const int &n is more preferred because:

  1. Using int n simply copies the array elements to the variable n during each iteration. This is not memory-efficient.
  2. &n, however, uses the memory address of the array elements to access their data without copying them to a new variable. This is memory-efficient.
  3. We are simply printing the array elements, not modifying them. Therefore, we use const so as not to accidentally change the values of the array.

Example 2: Take Inputs from User and Store Them in an Array

#include <iostream>
using namespace std;
int main() {
    int num[5];
                                  
    cout << "Enter 5 Integers: " << endl;
                                  
    //  store input from user to array
    for (int i = 0; i < 5; ++i) {
        cin >> num[i];
    }
                                  
cout << "The Array is: ";
                                  
//  print array elements
for (int n = 0; n < 5; ++n) {
        cout << num[n] << "  ";
    }
                                  
    return 0;
}

Output

Enter 5 numbers: 
5
8
1
-14
4
The numbers are: 5  8  1  -14  4

Once again, we have used a for loop to iterate from i = 0 to i = 4. In each iteration, we took an input from the user and stored it in num[i].

Then, we used another for loop to print all the array elements.


Example 3: Find the Sum and Average of Array Elements Using for Loop

#include <iostream>
using namespace std;
int main() {

    // initialize an array without specifying size
    double num[] = {2, 5, 6, 10, 15, 2}, sum = 0, count = 0, average;
    cout << "The numbers are: ";
                                  
    //  print array elements with the use of range-based for loop
    for (const double &n : num) {
        cout << n << "  ";
        //  calculate the sum of numbers
        sum += n;                       
        // count the no. of array elements
        ++count;
    }
    // print the sum of numberrs
    cout << "\nThe Sum of numbers = " << sum << endl;
                                  
    // find & print the average of numbers
    average = sum / count;
    cout << "The Average of numbers = " << average << endl;
                                  
    return 0;
}

Output

The numbers are: 2  5  6  10  15  2
Their Sum = 40
Their Average = 6.66667

Working of above program

  1. We have initialized a double array named num but without specifying its size.
  2. We also declared three double variables sum, count, and average.

    Here, sum =0 and count = 0.
  3. Then we used a range based for loop to print the array elements. In each iteration of the loop, we add the current array element to sum.
  4. We also increase the value of count by 1 in each iteration, so that we can get the size of the array by the end of the for loop.
  5. After printing all the elements, we print the sum and the average of all the numbers. The average of the numbers is given by average = sum / count;

Note: We used a ranged for loop instead of a normal for loop.

A normal for loop requires us to specify the number of iterations, which is given by the size of the array.

But a ranged for loop does not require such specifications.


Array Out of Bounds

If we declare an array of size 10, then the array will contain elements from index 0 to 9.

However, if we try to access the element at index 10 or more than 10, it will result in Undefined Behaviour.


Advantages of an Array in C++

  • Random access - Random access of element using array index.
  • Code Optimization - Use of less code as it creates a single array of multiple elements.
  • Easy to access - Easy access to all the elemnts.
  • Easy to traversing - Traversal through the array becomes easy until a single loop.
  • Easy to sorting - Sorting becomes easy as it can be accomplished by writing less code.

Disadvantages of an Array in C++

  • Fixed size - Allows a fixed number of elements to be entered which is decided at the time of decleration. Unlike a linked list, an array in c++ is not dynamic.
  • Inserting and deletion of elemnts can be costly since the elemnts are needed to be managed in accordance with the new memory allocation.

Some Facts about Array in C++

  • Access Array elemnets - Array elements are accessed by using an integer index.
  • No Index Out of bound - There is no index out of bound checking in C++.
  • Contiguous Memory location - Elements are stored at Contiguous memory location inside an array.

Next Tutorial

We hope that this tutorial helped you develop better understanding of the concept of Arrays in C++.

Keep Learning : )

In the next tutorial, you'll learn about C++ Multidimensional array.

- Related Topics