Hey gang! Here are my solutions to the chapter 3 exercises. If anyone needs help or would like me to provide an explanation to my solutions, please feel free to DM me!
Minimum:
function min(_first, _second) {
if (_first > _second) {
return _second;
}
else {
return _first;
}
}
// testing (must be in the html script tag)
let minimum = min(6, 7);
document.write("<h1>" + minimum + "</h1>");
Recursion:
function isEven(_number) {
while(true) {
if (_number == 1) {
return false;
}
if (_number == 0) {
return true
}
_number = _number - 2;
}
}
// testing (must be in the html script tag)
document.write("<h1>" + isEven(75) + "</h1>");
If -1 is used, the program hangs. Therefore to solve this issue, Another branch must be added to check whether the number passed is positive or not. Then, the exact same structure above is used but instead of subtracting 2, we add it as seen below.
function isEven(_number) {
while(true) {
if (_number == 1) {
return false;
}
if (_number == 0) {
return true
}
if (_number < 0) {
_number = _number + 2;
}
else {
_number = _number - 2;
}
}
}
// testing (must be in the html script tag)
document.write("<h1>" + isEven(-75) + "</h1>");
Bean counting:
function countBs(_string) {
let end = _string.length - 1;
let count = 0;
for (let i = 0; i <= end; i ++) {
if (_string[i] == "B") {
count++;
}
}
return count;
}
// testing (must be in the html script tag)
document.write("<h1>" + countBs("BananaBVB") + "</h1>");
function countLetter(_string, _toBeCounted) {
let end = _string.length - 1;
let count = 0;
for (let i = 0; i <= end; i ++) {
if (_string[i] == _toBeCounted) {
count++;
}
}
return count;
}
// testing (must be in the html script tag)
document.write("<h1>" + countLetter("BananaBVB", "n") + "</h1>");