4.0 Arrays
File Location
Right click on your solution
Go to Add > New Project and select Console App (.NET Framework)
Name it
Arrays
Discussion
An array stores a collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at similar memory locations.
Visualization
Declaring an array that will hold string values
Name of the array
Using keyword
new
to instantiate a new arrayWill hold string values
The array will hold 4 different values
Putting values into the array. For the first example, we say the 0 index of this array will hold the value
Macaroni
.
Declaration
To declare an array, it will look something like this datatype[] arrayName;
datatype
is used to specify the type of elements in the array []
specifies that it's an array arrayName
specifies the name of the array
Example:
decimal[] bankBalances;
Initializing an Array
The difference between declaring and initializing is when you declare it, it is first just a reference type. After you initialize it using the new
keyword, you create a new instance that you can assign values to.
Above, we assigned the first value of the array, index 0, to have the value of 4500. You can also assign values to the array at the time of declaration by following the example below.
decimal[] bankBalance ={2340.0, 4523.69, 3421.0}
or
int [] marks = new int[5] {99, 98, 92, 97, 95}
or
int [] marks = new int[] {99, 98, 92, 97, 95}
Accessing Array Elements
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example,
decimal johnBalance = bankBalance[3];
Array Examples
In the next couple modules, we will work through how to work with data within arrays and show how arrays can be useful. Before moving onto the next module, try creating an array listing some of the topics you have gone over in class so far.
Next: Loops
Last updated