Data storage.
Suppose you have developed a computer game called "User Hostile" in which players compete against convoluted and unfriendly computer interface. Now you need to write a program that tracks the monthly sales of this game over a five year period. Or let's say you need to inventory Hacker Hero Trading Cards.
Very soon you will come to the conclusion that you need more than simple basic data types to store and process information.
Arrays. Introduction.
To make it easier to work with large amounts of data, a group of cells is given a common name. Such a group of cells is called an array.
Array – it is a group of memory cells of the same type, located side by side and having a common name. Each cell in the group has a unique number.
There are three things you need to learn when working with arrays:
x allocate memory of the required size for the array;
x write data to the desired cell;
x read data from a cell.
Create an array.
When creating an array, space is allocated in memory (a certain number of cells).
1) Arrays can be created by simply enumerating elements:
int
[] nums =
< code>new int
[] { 1, 2, 3, 5 };
int
means that all objects in the array are integers.
In place of int
there can be any other data type. For example,
string[] names = ["Vasya", "Peter", "Fedya"];
2)
We can not immediately specify the values of the array, but simply create an array of the length we need.
int
[] nums =
new
int
[4];
3) An array always "knows" your size. The size of the array a can be found like this:
a.Length;
Often the size of the array is stored in a separate variable so that the program can be easily changed to work with a different array size. Example:
int N = 10; // store the size of the array in variable N
int[] nums = new int[4]; // create an array of size N
Console.Write(nums.Length); // display the size of the array
The size of the array can be set from the keyboard.