PLEASE HELP, I don't understand the logic behind both programs giving 100 and 2 as their output. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 8

PLEASE HELP, I don't understand the logic behind both programs giving 100 and 2 as their output.

// First program function tobin(num) { var res=""; while(num>0){ res=num%2+res; num=Math.floor(num/2); } return res; } document.write(tobin(4)); // Second program var a = 10, b = 20, c = 30; if (c > b > a) { console.log('1'); } else { console.log('2'); }

9th Jul 2019, 4:21 PM
eMBee
eMBee - avatar
3 Answers
+ 13
First: It's just converted to binary. If you have never seen something like this, you can just run through it: res = num % 2 + res -> num % 2 is 0, so res is 0 num = Math.floor(num / 2) -> num is 2 num % 2 is still 0, so res is 00 Math.floor(num / 2) -> num is 1 num % 2 is 1, so res is 100 Math.floor(num / 2) is 0, so the loop stops there Second: c > b is true, meaning it will be converted to true > a. True converted to a number is one, and 1 > 10 is false.
9th Jul 2019, 4:35 PM
Airree
Airree - avatar
+ 4
Thanks Airree, that was crisp and crystal clear
9th Jul 2019, 7:13 PM
eMBee
eMBee - avatar
+ 2
The first program outputs (1+3+5+7+9)*4=100 The second program outputs (30>20)==1(true) <10==false (0) = 2 (console.log) 🤔🤗
11th Jul 2019, 4:53 AM
Sanjay Kamath
Sanjay Kamath - avatar