Showing posts with label int array. Show all posts
Showing posts with label int array. Show all posts

13 Nov 2011

C# Working With int Array 1


Int array example

As an introduction to the C# array type, let's look at a simple example program that allocates and initializes an integer array of three elements. Please notice how the elements can be assigned to or read from using the same syntax (values[int]). The array is zero-based; we also demonstrate the foreach loop upon it.
Program that uses an array [C#]

using System;

class Program
{
static void Main()
{
// Use an array.
int[] values = new int[3];
values[0] = 5;
values[1] = values[0] * 2;
values[2] = values[1] * 2;

foreach (int value in values)
{
Console.WriteLine(value);
}
}
}

Output

5
10
20

C# Working With Int Array


This first example shows how you can declare int arrays in four different ways. The first three arrays declared below are declared on single lines, while the fourth array is declared by individual assignment of the elements.
Code:
using System;

class Program
{
static void Main()
{
int[] arr1 = new int[] { 3, 4, 5 }; // Declare int array
int[] arr2 = { 3, 4, 5 }; // Another
var arr3 = new int[] { 3, 4, 5 }; // Another

int[] arr4 = new int[3]; // Declare int array of zeros
arr4[0] = 3;
arr4[1] = 4;
arr4[2] = 5;

if (arr1[0] == arr2[0] &&
arr1[0] == arr3[0] &&
arr1[0] == arr4[0])
{
Console.WriteLine("First elements are the same");
}
}
}

Output

First elements are the same