Arrays in c++


  • An array is a variable that refers to a block of memory that, like a vector, can hold multiple values simultaneously.
  • An array has a name, and the values it contains are accessed via their position within the block of memory designated for the array.
  • Also like a vector, the elements within an array must all be of the same type. Arrays may be local or global variables.
  • Arrays are built into the core language of both C and C++. This means you do not need to add any #include directives to use an array within a program.
  • Arrays allow us to do something similar with variables. An array is a set of consecutive memory locations used to store data. Each item in the array is called an element

Defining Arrays

An array must be defined just like any other object. The definition includes the array name and the type and number of array elements.

    Syntax:
     type name[count]; // Array name
    In the above syntax description, count is an integral constant or integral expression containing only constants.

    Example:
     float arr[10]; // Array arr
    This statement defines the array arr with 10 elements of float type. The object arr itself is of a derived type, an “array of float elements” or “float array.”
    An array always occupies a contiguous memory space. In the case of the array arr, this space is 10*sizeof(float) = 40 bytes.

Example

    //computes the total and average of five numbers
    
    #include <iostream.h>
    
    float data[5]; // data to average and total
    float total; // the total of the data items
    float average; // average of the items
    main ()
    {
     data[0] = 34.0;
     data[1] = 27.0;
     data[2] = 46.5;
     data[3] = 82.0;
     data[4] = 22.0;
    
     total = data[0] + data[1] + data[2] + data[3] + data[4];
     average = total / 5.0;
     cout << "Total "<< total << " Average " << average << '\n';
     return (0);
    }
    

Output

    Total 211.5 Average 42.3