The formula to find the nth triangular number is n * (n+1) / 2
. Here's the code to find the nth triangular number in JavaScript using a for loop:
index.tsx261 chars11 lines
In this code, we define a function findTriangularNumber
that takes an integer n
as input. We initialize a variable triangularNumber
to 0. We then use a for loop to iterate from 1 to n
. At each iteration, we add the current value of i
to triangularNumber
. Finally, we return triangularNumber
.
We can test our function by calling it with different values of n
and checking if it returns the correct output.
gistlibby LogSnag