Get The Nth Element Of Array In C#
Code snippet for how to Get The Nth Element Of Array In C# with sample and detail explanation
C# is a versatile programming language with a wide range of built-in functionality. In this article, we will discuss how to get the nth element of an array using C#.
Code snippet for Getting the Nth Element of Array
Let’s first initialize an array and then gather the nth element:
using System;
class Program
{
static void Main()
{
int[] array = {1, 2, 3, 4, 5};
int nth = 3;
Console.WriteLine($"The {nth}rd element of the array is: {array[nth - 1]}");
}
}
Code Explanation for Getting the Nth Element of Array
Let’s break the code down line by line:
-
We start with
using System;
. Here we are simply importing the System namespace, which contains fundamental classes and base classes that define commonly-used value and reference data types. -
The
class Program
is where we are defining our new class. In C#, every line of code that runs needs to be inside a class. -
static void Main()
is the Main method which is the entry point of a C# application. -
In the line
int[] array = {1, 2, 3, 4, 5};
, we declare and initialize an array of integers. This array contains 5 elements. -
int nth = 3;
Here, we’re declaring a variablenth
which denotes the position of the element we want to retrieve. -
Here comes the important line where we actually retrieve the nth element from the array:
Console.WriteLine($"The {nth}rd element of the array is: {array[nth - 1]}");
-
We’re using Console.WriteLine to print a line to the console.
-
The
$"The {nth}rd element of the array is: {array[nth - 1]}"
is an interpolated string. The{nth}
and{array[nth - 1]}
are placeholders that get replaced by the value of nth and the nth-1st element of the array respectively when the string gets printed. -
The
array[nth - 1]
is how we retrieve the nth element from the array. As we know, arrays are 0-indexed in C#. Hence to get the nth element, we need to subtract one from n.
-
-
Thus, when we run this program, it will output:
The 3rd element of the array is: 3
.
This wraps up our step by step tutorial on how to get the nth element of an array in C#. As we’ve seen, C# provides a simple and straightforward way to access array elements.