Defining Arrays

Describes how to define and use arrays, illustrating one-dimensional and multidimensional arrays, C strings and class arrays.

Defining Arrays

The array arr in memory

Sample program

// array.cpp
// To input numbers into an array and output after.
// ----------------------------------------------------
#include <iostream>
#include <iomanip>
using namespace std;
   
int main()
{
   const int MAXCNT = 10;       // Constant
   float arr[MAXCNT], x;        // Array, temp. variable
   int i, cnt;                  // Index, quantity
   
   cout << "Enter up to 10 numbers \n"
        << "(Quit with a letter):" << endl;
   for( i = 0; i < MAXCNT  &&  cin >> x; ++i)
      arr[i] = x;
   cnt = i;
   cout << "The given numbers:\n" << endl;
   for( i = 0; i < cnt; ++i)
      cout << setw(10) << arr[i];
   cout << endl;
   return 0;
}
An array contains multiple objects of identical types stored sequentially in memory. The individual objects in an array, referred to as array elements, can be addressed using a number, the so-called index or subscript. An array is also referred to as a vector.

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.

Index for Array Elements

The subscript operator [] is used to access individual array elements. In C++ an index always begins at zero. The elements belonging to the array arr are thus
arr[0], arr[1] , arr[2], ... , arr[9]
The index of the last array element is thus 1 lower than the number of array elements. Any int expression can be used as an index. The subscript operator [] has high precedence, just like the class member operators . and -> .
No error message is issued if the index exceeds the valid index range. As a programmer, you need to be particularly careful to avoid this error! However, you can define a class to perform range checking for indices.
You can create an array from any type with the exception of some special types, such as void and certain classes. Class arrays are discussed later.
Example:
short number[20];          // short array
for( int i=0; i < 20; i++ )
   number[i] = (short)(i*10); 
This example defines an array called number with 20 short elements and assigns the values 0, 10, 20, ... , 190 to the elements.

 

Post a Comment

0 Comments