find the nth triangular number in csharp

To find the nth triangular number, we can use a simple formula:

nthTriangularNumber = n * (n + 1) / 2

where n is the given index of the triangular number.

Here's an implementation in C# using a loop to handle a case where n is less than or equal to 0:

main.cs
public static int GetNthTriangularNumber(int n)
{
    if (n <= 0)
    {
        throw new ArgumentException("n must be greater than 0");
    }

    int result = 0;
    for (int i = 1; i <= n; i++)
    {
        result += i;
    }

    return result;
}
252 chars
16 lines

We can simplify this further using the formula mentioned earlier:

main.cs
public static int GetNthTriangularNumber(int n)
{
    if (n <= 0)
    {
        throw new ArgumentException("n must be greater than 0");
    }

    return n * (n + 1) / 2;
}
174 chars
10 lines

Now we can call this function with any positive integer n to get the nth triangular number.

gistlibby LogSnag