2.Arrays-One-Dimensional
2.Arrays-One-Dimensional
ONE DIMENSIONAL
Objectives
▷ Define arrays;
▷ Declare and create an array;
▷ Access elements of an array
2
What is an Array?
3
What is an Array?
4
Array
Elements
12 15 20 16 1 7 9 17
0 1 2 3 4 5 6 7
Index
5
Array Components
Element Index/Subscript
▷ how each of these ▷ specifies the position of the
objects are called. elements of the array. How
▷ the values inside the the elements of an array are
array numbered consecutively as
0,1,2, 3...
▷ the index of an array always
starts with 0.
6
Declaring an Array
datatype[] arrayName;
7
where:
8
Example:
double [] balance;
int [] num;
9
Initializing an Array:
11
Assigning values to Array:
13
Assigning values to Array:
14
Accessing Array Elements
Console.WriteLine(cars[2]);
Console.WriteLine(cars[0]);
Console.WriteLine(cars[1]);
Console.WriteLine(cars[3]);
Console.WriteLine(cars[4]);
16
Example 1:
string [] cars = {“Mazda”, “Subaru”, “Toyota”, “Chery”, “BMW”};
17
Example 2:
int[] evenNums = { 2, 4, 6, 8, 10 };
18
Example 3:
int[] evenNums = { 2, 4, 6, 8, 10, 12 };
int temp=0;
for(int x=0; x<evenNums.Length; x+=2)
{
temp=evenNums[x];
evenNums[x]=evenNums[x+1];
evenNums[x+1]=temp;
}
for(int y=0; y<evenNums.Length; y++)
Console.Write(evenNums[y] + " ");
19
Array Index out of bounds
20
Array Index out of bounds
// Outputs 4
22
Array Sort
23
Array Sort
24