Given a positive integer n, find the sum of the first n natural numbers.
Examples :
Input: n = 1
Output: 1
Input: n = 3
Output: 6
Explanation: 1 + 2 + 3 = 6
Input: n = 4
Output: 10
Explanation: 1 + 2 + 3 + 4 = 10
Method 1: Formula Based
Sum of first n natural numbers = (n * (n+1)) / 2
Deluge Code:
n= 4;
sum = (n * (n+1)) / 2;
info sum;
Method 2: Using Loop
// set number of times to iterate through loop (plus 1)
n=4;
// create a string with this many spaces using leftpad
iterationList = leftpad(" ", n).replaceAll(" ",",");
// convert string to a list
l_GeneratedList = iterationList.toList();
sum = 0;
// loop through generated list
for each index v_Index in l_GeneratedList
{
sum = sum + v_Index;
}
info sum;