Array Index
In this chapter you will learn:
- Array Declaration with initialization
- How ro assign value to an array
- Set array element value by index(subscript)
- Index out of range exception
- What to do with IndexOutOfRangeException
Array Declaration with initialization
The general form for initializing a one-dimensional array is shown here:
type[ ] array-name = { val1, val2, val3, ..., valN };
using System; //from ja va 2 s. co m
class MainClass
{
static void Main()
{
string[] languages = new string[9]{"C#", "COBOL", "Java","java2s.com", "Visual Basic", "Pascal"};
// Retrieve 5th item in languages array (Visual Basic)
string language = languages[4];
Console.WriteLine(language);
}
}
Assign value to array
using System; //ja v a 2 s.c o m
class MainClass {
public static void Main() {
int[] sample = new int[10];
int i;
for(i = 0; i < 10; i = i+1) {
sample[i] = i;
}
for(i = 0; i < 10; i = i+1) {
Console.WriteLine("sample[" + i + "]: " + sample[i]);
}
}
}
The code above generates the following result.
Element by Index
using System; // jav a2s . c om
class MainClass {
public static void Main() {
int[] nums = new int[10];
int avg = 0;
nums[0] = 99;
nums[1] = 10;
nums[2] = 100;
nums[3] = 18;
nums[4] = 78;
nums[5] = 23;
nums[6] = 63;
nums[7] = 9;
nums[8] = 87;
nums[9] = 49;
for(int i=0; i < 10; i++) {
avg = avg + nums[i];
}
avg = avg / 10;
Console.WriteLine("Average: " + avg);
}
}
The code above generates the following result.
Index out of range exception
When reference an index behind the length of an array C# generates and throws IndexOfOfRange exception.
The following code generates the IndexOutOfRange exception.
using System;/*from jav a 2 s . c om*/
class Program
{
static void Main(string[] args)
{
int[] intArray = new int[3];
Console.WriteLine(intArray[10]);
}
}
The output:
Catch IndexOutOfRangeException
An attempt to write to a nonexistent array element: IndexOutOfRangeException
using System;/*from j ava 2 s . co m*/
class MainClass
{
public static void Main()
{
try
{
int[] intArray = new int[5];
for (int i = 0; i <= intArray.Length; i++){
intArray[i] = i;
Console.WriteLine(intArray[i]);
}
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("IndexOutOfRangeException occurred");
Console.WriteLine("Message = " + e.Message);
Console.WriteLine("Stack trace = " + e.StackTrace);
}
}
}
The code above generates the following result.
The for loop should be the following and <=
should be <
.
for (int i = 0; i < intArray.Length; i++){
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » Array