File tree 1 file changed +34
-0
lines changed
1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Step By Step Iterative Solution
2
+ function SimpleAdding ( num ) {
3
+ // Declare a variable to hold our answer
4
+ var sum = 0 ;
5
+
6
+ // Loop through all numbers between num and 1 inclusive...
7
+ for ( var i = num ; i > 0 ; i -- ) {
8
+ // ...adding i to our answer each time.
9
+ sum += i ;
10
+ }
11
+ // Finally, we return our answer.
12
+ return sum ;
13
+ }
14
+
15
+ // Step By Step Recursive Solution
16
+
17
+ function SimpleAdding ( num , sum ) {
18
+ // If no argument is passed for sum (Coderbyte will always only pass 1 argument into our function), we set it to 0
19
+ sum = sum || 0 ;
20
+
21
+ // Next, we set our base case to stop the function from recursing when our input number equals 0...
22
+ if ( num === 0 ) {
23
+ // ...and return our answer
24
+ return sum ;
25
+ }
26
+
27
+ // Each time we recurse through our function, we add the number to our sum variable (sum += num)...
28
+ sum += num ;
29
+ // ...and decrease num by 1 using the decrement operator
30
+ num -- ;
31
+
32
+ // We return the function again and continue to add num to curSum and decrement num by 1 until num reaches 0.
33
+ return SimpleAdding ( num , sum ) ;
34
+ }
You can’t perform that action at this time.
0 commit comments