Question:
Given two values, write a Javascript program to find out which one is nearest to 100.
Answer:
function nearHund (num1, num2) {
if (num1 > num2 && num1 <= 100) {
return num1;
} else if (num1 < num2 && num2 <= 100) {
return num2;
} else if (num1 > num2 && num2 > 100) {
return num2;
} else if (num1 < num2 && num1 > 100) {
return num1;
} else {
return num1;
}
}
> we declare a function 'nearHund'
> it has two parameters 'num1' and 'num2'
> we open if / else statements to check if the numbers are near the number '100'
> there are mainly 5 possibilities that need to be checked
>> first is to check if 'num1' is greater than 'num2' and 'num1' is less than or equal to 100
>>> if this condition is true then we want to return 'num1'
>> second is to check if 'num2' is greater than 'num1' and 'num2' is less than or equal to 100
>>> if this condition is true then we want to return 'num2'
>> third is to check if 'num1' is greater than 'num2' and 'num2' is more than or equal to 100
>>> if this condition is true then we want to return 'num2'
>> fourth is to check if 'num2' is greater than 'num1' and 'num1' is more than or equal to 100
>>> if this condition is true then we want to return 'num1'
>> fifth and the easiest one is to check if both 'num1' & 'num2' are same
>>> if this condition is true then we want to return any parameter 'num1' or 'num2'
No comments:
Post a Comment