find the nth triangular number in javascript

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.tsx
function findTriangularNumber(n) {
  let triangularNumber = 0;
  for (let i = 1; i <= n; i++) {
    triangularNumber += i;
  }
  return triangularNumber;
}

console.log(findTriangularNumber(5)); // Output: 15
console.log(findTriangularNumber(7)); // Output: 28
261 chars
11 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