Monday 20 February 2012

The Basics of a One-dimensional Array in C++

Here is a discussion on creating and using a one-dimensional array in C++.

An array is a variable of one data type with multiple values. In C++, each array holds values of the same date type (i.e., all integers or all floating point numbers). It’s a computer version of a matrix from mathematics. A one-dimensional array is similar to a matrix with one row or one column.

An array is created by specifying the data type (e.g., char, int) followed by a user-defined variable name and the maximum number of elements in square brackets.

type name[size];

For example, this declaration

int myArray[10];

creates an array called myArray with 10 elements of type integer.

Each element of the array is accessed by an index. The base index is 0 and increases by 1 to the size of the array less one (size – 1). The indices of an array with 10 elements are 0 to 9.

You access an element of an array by specifying its name followed by the specific index number in square brackets. There can be spaces between the name of the array and the square brackets, but convention is to not have a space.

variable_name[index]  // No space.
variable_name [index] // Space in between.

For example,

myArray[0] = 10;

stores 10 in the first element of the array.

Unlike a stack, an array can be accessed in any order.

The data of an array is stored sequentially in memory and can be accessed directly. The amount of memory used varies with the data type.

Sample Code.

The sample code was created in MS Visual C++ as a Windows Form Application. It contains a form (Form1) that displays when the program runs. The sample code, contained in the Form Load Event, executes and adds text to a RichTextBox named rtOut.

// Declare a one-dimension array of integers.
int sample[10];
rtOut->Text = "Declare one-dimension array: ";
rtOut->Text += "int sample[10]; \n\n";

// Counter.
int i = 0;

// Load array with 0 to 9.
// The value stored in the array is its index.
for (i; i < 10; i++) sample[i] = i;

// Show content.
// Note the counter i is reset to 0.
for (i = 0; i < 10; i++)
{
rtOut->Text += "The value of sample[" + i + "] is " + sample[i] + ".\n";
}

Output:

Declare one-dimension array: int sample[10];

The value of sample[0] is 0.
The value of sample[1] is 1.
The value of sample[2] is 2.
The value of sample[3] is 3.
The value of sample[4] is 4.
The value of sample[5] is 5.
The value of sample[6] is 6.
The value of sample[7] is 7.
The value of sample[8] is 8.
The value of sample[9] is 9.

No comments:

Post a Comment