c++

C++ Arrays

An Array in C++ is nothing but a homogeneous collection of multiple data elements . It is a linear data structure. Arrays are opened from both the end and it also allow us the random access of the elements , there is no such sequential rule to follow for accessing the data you can choose the data element of your choice.

For example we want to store age of the employees working for company. Suppose that the number employees are 63 then instead of creating 63 separate variables ,we can simply create an array:

int age[63];

In the above example age is an array that can hold a maximum of 63 elements of data type.


Syntax of Declaring an Array in C++

data_type variable_name[size];

Important points to remember :

  1. [size] is number of values arrays can hold.
  2. This size must be an integer constant.

For example,

  1. int, char, float - data type of element to be stored.
  2. Roll nos, grades, per - names of arrays.
  3. 40, 14, 20 - size of the array.

Syntax errors while declaration of array

  1. The size of array must always be a constant in Turbo C compiler, variables cannot be used as size of array. However, GCC compiler allows variable also in the size of array.
  2. Size is a mandatory feature in array declaration and cannot be left blank. This rule is followed by all the compiler.
  3. The minimum size of any array can be 1 ,you cannot create less then that.

Important : While declaring the array the number of square braces [ ] used determines that of how many dimension the array will be.Currently in the above example are single dimensional.


Access element in C++ array

In C++, each element in an array is associated with a number. The number is known as array index. We can access elements of an array by using those indexes. Array elements are accessed by using an integer index.

Note : Index of array starts from 0 and goes up to n-1 .

// syntax to access array elements 
array[index];
image

Points to remember :

  1. As we can see that the array index start from 0 , which simply tell us that x[0] is the first element to be stored at index number 0.
  2. If in case, the size of an array is n, so in that case the last element will be stored at index number (n-1) . As you can see in the above figure that 5 is the last element stored in x[5].
  3. In Array, elements have addresses which are successive. In the above figure let us suppose the starting address of x[0] is 2020d. Then, the address of the next element x[1] will be 2024d, the address of x[2] will be 2028d upto n.

Here, as we can see that the size of each element is increased by 4. Because the size of int is 4 bytes.


Initialization of array in C++

The initialization for an array is basically a list of constant expressions that are separated by commas and are enclosed in braces { } . The initializer is lead up by = sign . You do not need to initialize all elements in an array. In C++, We can initialize an array during declaration of it . See below.

int x[6] = {19, 10, 8, 17, 9, 15};

Another method to initialize array during declaration :

int x[] = {19, 10, 8, 17, 9, 15};

In the above case we did’t mentioned the size of the array. In that case, the compiler automatically computes the size based on the number of constants after = sign.


C++ array with empty members

In C++, if an array has a size n, so we can store n number of elements in the array but if we have array of n and you store less than n number of elements then what will happen ?

Look at the example below :

int x[10] = {3, 7, 13, 6, 4};

In the above case the array x has a size of 10. but, we have initialized only 5 elements. In that case, the compiler automatically assigns some random values to the remaining places and this random value is simply called as garbage value.


Inserting and printing array elements

int mark[5] = {19, 10, 8, 17, 9}

// change 4th element to 9
mark[3] = 9;

// take input from the user
// store the value at third position 
cin >> mark[2];

// take input from the user
// insert at ith position 
cin >> mark[i-1];

// print first element of the array 
cout << mark[0];

// print ith element of the array 
cout >> mark[i-1];

Example 1: Displaying array elements

#include <iostream>

using namespace std;

int main() {
    roll nos[7] = { };

    cout << "roll nos are: ";

    // Printing array elements
    // using range based for loop

    for (const int &n : roll nos) {
        cout << n << " ";
    }

    cout << "\n roll nos are: ";

    // Printing array elements
    // using traditional for loop

    for (int i = 0; i < 7; ++i) {
        cout << roll nos[i] << " ";
    }

    return 0;
}

Output :

roll nos are: 3 6 11 16 21 24 29
Roll nos are: 3 6 11 16 21 24 29

In the above example we have used a for loop to iterate from i = 0 to i = 6. In each iteration, we have printed numbers[i].

Example 2: Taking inputs from user and storing them in array

#include <iostream>

using namespace std;

int main() {
    int ages[10];

    cout << "kindly enter 10 ages: " << endl;

    // store input from user to array
    for (int i = 0; i < 10; ++i) {
        cin >> ages[i];
    }

    cout << " entered ages are: ";

    // print array elements
    for (int n = 0; n < 10; ++n) {
        cout << ages[n] << " ";
    }

    return 0;
}

Output :

Kindly enter 10 ages:
5
9
15
19
22
24
29
36
45
53
entered ages are: 5 9 15 19 22 24 29 36 45 53

In the above example we again, used a for loop to iterate from i = 0 to i = 9. In each iteration, we took an value from the user and stored it in ages[i].Then, we used another for loop to print all the array elements.

Example 3: Displaying sum and average of array elements using for loop

#include <iostream>

using namespace std;

int main() {

    // initialize an array without specifying size
    double nums[] = {10, 20, 30, 40};

    double sum = 0;
    double count = 0;
    double average;

    cout << " nums are: ";

    // print array elements
    // use of range-based for loop
    for (const double &n : nums) {
        cout << n << " ";

        // calculate the sum
        sum += n;

        // count the no. of array elements
        ++count;
    }

    // print the sum
    cout << "\n Sum is = " << sum << endl;

    // find the average
    average = sum / count;

    cout << " Average is = " << average << endl;

    return 0;
}

Output :

The nums are: 10 20 30 40
Sum is = 100
Average is = 25

Description of above code :

In the above program, we have initialized a double array of undefined size whose name is nums. Along with nums we have also declared 3 elements of double data type whose names are sum, count, average. We have used a ranged loop in it, (we have done so because a normal for loop require to specify the number of iterations, which is given by size of array, but a ranged for loop does not any such thing). In each iteration, we added current array element to the sum. Then we incremented the value of count by 1 by using pre-increment operator so that we get the size of array at the end. After printing all element we printed sum and average of nums with the help of cout. The average of the nums are given by the formula average = sum/count;.


Out of bounds array in C++

The array out of bounds error is a special case of the buffer overflow error. This error usually pops up when the index used to address array items surpass the allowed value. It's the area outside the array bounds which is being addressed.This could me understood with the help of an example suppose that we declared array of size 5, then array will be keeping data elements from index number 0 to 4.On the other hand, if we try to access the element at index number 5 or you try to put more data element in it then it will result in Undefined Behaviour.