CPP Arrays

Working Array Variables in C++.

An array in the RAM:

  • Array is a sequential collection of data storage locations.
  • An array holds the same type of data and can be
    primitives (int, double, long ...) and any Object type.
    long LongArray[100];
  • This is an array, LongArray, holding 100 elements of long integers.
  • The square brackets are in three different ways:
    1. When you want to define an array.
    2. When you want to set an object into the array (as shown above).
      LongArray[index]=100;
      where index is an offset into the array with the value of 0 -> N.
    3. When you want to get a object from the array.
      long item = LongArray[index];
      where index is an offset into the array with the value of 0 -> N.

Initializing Arrays

You can Initialize an array in different ways:
int IntegerArray[5] = { 10, 20, 30, 40, 50 };    // OK
int IntegerArray[] = { 10, 20, 30, 40, 50 };     // OK
int IntegerArray[5] = { 10, 20, 30, 40, 50, 60}; // Compiler error as too many
int IntegerArray[5] = {10, 20};                  // legal but bad

Multidimensional arrays

You can have multidimensional arrays in this way:
// Declaring Multidimensional Arrays (8*8 = 64 of long integers)
long Board[8][8];

// Initializing Multidimensional Arrays  
int theArray[5][3] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };

// Or for clarity:
int theArray[5][3] = {  {1,2,3},
    {4,5,6},
    {7,8,9},
    {10,11,12},
    {13,14,15} };
Program example using arrays:
#include <iostream>
using namespace std;

int main() {
  int SomeArray[2][5] = { {0,1,2,3,4}, {0,2,4,6,8}};
  for (int i = 0; i<2; i++) {
    for (int j=0; j<5; j++) {
      cout << "SomeArray[" << i << "][" << j << "]: ";
      cout << SomeArray[i][j]<< endl;
    }
  }
  return 0;
}
When we run this application the result will be:
SomeArray[0][0]: 0
SomeArray[0][1]: 1
SomeArray[0][2]: 2
SomeArray[0][3]: 3
SomeArray[0][4]: 4
SomeArray[1][0]: 0
SomeArray[1][1]: 2
SomeArray[1][2]: 4
SomeArray[1][3]: 6
SomeArray[1][4]: 8

You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.