Why the output of this code is 337 (JavaScript)? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why the output of this code is 337 (JavaScript)?

function mlt(a, b) { if (!(a&&b)) { return 0; } else if (b == 1) { return a; } else { return (a + mlt(a, b - 1)); } } document.write(mlt(3, 11)); document.write(mlt(7, 1));

28th Oct 2018, 7:09 PM
Federico Riva
3 Answers
+ 4
This function is used for multiplying numbers. The first case with 3, 11 => enter in the else condition until b equals 1 => 3 + mlt (3, 10) + 3 +mlt (3, 9) + ... + 3 + mlt(3, 1) and return the result => 11*3 = 33. The same is with parameters 7, 1 => result 7*1 =7. So the final result is 337. Hope it helps you :)
28th Oct 2018, 7:26 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 2
It's an example for recursion. Because of document.write there's no line break between 33 and 7.
28th Oct 2018, 7:30 PM
Mirko Klotzsche
Mirko Klotzsche - avatar
+ 2
TheWhiteCat thanks very much
28th Oct 2018, 9:58 PM
Federico Riva