Home »
.Net
Single dimensional arrays in C#
Learn: Single dimensional array in C#.Net, how to declare, read and print the elements of an array?
Just like other programming languages, in C# arrays are also used to hold similar type of data elements, they are user defined data types.
In C# arrays are also references.
Syntax of single dimensional array:
<data_type>[] variable_name = new <data_type>[SIZE];
Example:
int[] X = new int[100];
Here, new operator is used to allocate memory space for the array.
Initialization of single dimensional array:
int[] X = {1,2,3,4,5};
Here, X contains 5 elements. Indexing of array is starting from 0 to size-1.
We can access of X like this, X[0] contains value 1, X[1] contains value 2 and so on.
Consider the program:
using System;
namespace arrayEx
{
class Program
{
static void Main(string[] args)
{
int i = 0;
int[] X;
X = new int[5];
Console.Write("Enter Elements : \n");
for (i = 0; i < 5; i++)
{
Console.Write("\tElement[" + i + "]: ");
X[i] = Convert.ToInt32(Console.ReadLine());
}
Console.Write("\n\nElements are: \n");
for (i = 0; i < 5; i++)
{
Console.WriteLine("\tElement[" + i + "]: "+X[i]);
}
}
}
}
Output
Output:
Enter Elements :
Element[0]: 10
Element[1]: 20
Element[2]: 30
Element[3]: 40
Element[4]: 50
Elements are:
Element[0]: 10
Element[1]: 20
Element[2]: 30
Element[3]: 40
Element[4]: 50
Press any key to continue . . .