When to use while loop ?
Notes:
When to use while loop rather than for loop:
when you do not know ahead of time the number of iterations that you need to do, use while loop.
When you know exactly how many number of iterations need to be done use for loop.
var num=123;
var lastDigit=0;
var sumOfAllDigits=0;
lastDigit = num % 10; // 3
sumOfAllDigits = sumOfAllDigits + lastDigit; // 3
num = parseInt(num/10); // 12
lastDigit = num % 10; // 2
sumOfAllDigits = sumOfAllDigits + lastDigit; // 5
num = parseInt(num/10); // 1
lastDigit = num % 10; // 1
sumOfAllDigits = sumOfAllDigits + lastDigit; // 6
num = parseInt(num/10); // 0
document.write("Sum of all digits : ", sumOfAllDigits);
Interview Questions: