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.
For example, this declaration
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.
myArray = 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.
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.
rtOut->Text = "Declare one-dimension array: ";
rtOut->Text += "int sample; \n\n";
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";
Declare one-dimension array: int sample;
The value of sample is 0.
The value of sample is 1.
The value of sample is 2.
The value of sample is 3.
The value of sample is 4.
The value of sample is 5.
The value of sample is 6.
The value of sample is 7.
The value of sample is 8.
The value of sample is 9.