Chapter 3 Exercises

1- function a(e,f){

return Math.min(e,f);

}

console.log(a(77,99));

2- function isEven(n){

if(n===0){

return false;

}

if(n===1){

return true;

}

if(n===(n-2)){

return false;

}

}

console.log(isEven());

3- function countB(string){

//return a call to countChar with input and “B”

return countChar(string , ‘B’);

}

function countChar(string , character){

//do stuff

//create a result , set to 0

let result = 0;

//loop over the string

for(let i = 0 ; i < string.length ; i++) {

//if our character match input character

if(string[i] === character){

//increment our result by 1

result = result + 1 ;

}

}

//return a result

return result;

}

console.log(countB(“BBCBCBCBC”));

console.log(countChar(“kakerlakkkkkk” ,“k”));

1 Like

Recursion

var n = parseInt(prompt(“Enter number to test if it’s even”));
var answer = true; n = Math.abs(n);
console.log(isEven(n));

function isEven (n){
if (n == 1){answer = false;}
else if (n == 0){answer = true;}
else {
n = n - 2; isEven (n);
}
return answer;
}

Bean counting

var word = prompt(“Type your word”);
var ch = prompt(“Which character to count”);

function CountBs (word, ch){
var howmanyCH = 0;
for (i = 0; i < word.length; i++){
if (word[i] == ch){
var howmanyCH = howmanyCH + 1;
}
}
return howmanyCH;
}
console.log(CountBs(word, ch));

  • Question
    Ivan said in the Local and Global Variables video that if we define a variable outside of a function it will be recognized within the function as well.
    However in the Bean Counting exercise if I move the counter variable “var howmanyCH = 0” outside of the function then the program does not work, it returns undefined.
    What’s the problem?
1 Like

Hi @Andro,

Well, You defined your variable twice in your function. IThe compiler gets confused because of the same name in different contexts. Define it just once outside the function the use it accordingly –

var word = prompt('Type your word');
var ch = prompt('Which character to count');
var howmanyCH = 0;

function CountBs (word, ch) {
   for (i = 0; i < word.length; i++){
     if (word[i] == ch){
     howmanyCH = howmanyCH + 1;
     }
   }

return howmanyCH;
}

Hope this clarifies your doubt. Happy Learning!

2 Likes

Thank you for answering @Malik . When I try this out in the console it returns the correct value but also says “undefined” in the next line, is that a problem?

No, that is not a problem. That’s how the console logging in the browser console works when written directly. If you are writing console logs in your program however, the undefined should not be visible.

1 Like
  1. Minimum

function minnum(a,b) { if(a<b){console.log(a);}
else{console.log(b);}}

minnum(10,13); // ==>10

minnum(8,3); // ==>3

minnum(7,2); // ==>2

  1. Recursion
    function isEven(n) {
    if (n%2 == 0){return true;}
    else if (n%2 == 1|| n<0) {return false;}
    else{ return “??”;} }
    console.log(isEven(75)); // ==> false
    (-1); //==> false
    (50); //==> true

  2. Bean counting
    function countBs(string){
    var count = 0;
    for (var x = 0; x < string.length; x++){
    if (string[x] == “B”) {count++;}} return count;}
    console.log(countBs(“BBk”)) ; //==>2

function countChar(string, character){
var count = 0;
for(var y = 0; y < string.length; y++){
if(string[y] == character) {count++;}} return count;}
console.log(countChar(“Babccc”,“c”)) ; // ==>3

1 Like

Min

function min (a, b){
if (a < b) {
console.log(a + " is smaller than " + b)}
else {
console.log( a + " is larger than " + b)
}
}
console.log(min(75, 50));

Recursion - (found this really difficult)

function isEven (n) {
if (n == 0) return true;
else if (n == 1) return false;
else if (n < 0) return isEven (n-1);
else return isEven (n-2);
}

Beans

function countBs (string) {
let result = 0;
for (i = 0; i < string.length; i++) {
if(string[i] == ‘B’){
result = result + 1;
}
}
return result;
}

function countChar (string, count) {
let result = 0;
for (i = 0; i < string.length; i++) {
if(string[i] == count){
result = result + 1;
}
}
return result;
}

1 Like

has anyone tried dividing?

1 ```
function min(x, y) {
if (x < y) document.write("Smaller from " + x + " and " y " is " + x));
else document.write("Smaller from " + x + " and " y " is " + y));
else return document.write(“no minimum numbers are equal” );
}

2.function isEven(num)
   if (num < 0) num = -1 * num
 if (num === 0)
        return true;
    else if (num === 1)
        return false;
    else
        return isEven(num - 2);
}
3. ```
function countBs(string) {
let count = 0;
   for (let i = 0; i < string.length; i++){
       if (string[i] == "B") {
           count += 1;
             }
      }
}

function countChar(string, char) {
let count = 0;
 for (let i = 0; i < string.length; i++) {
   if (string[i] == char) {
     count += 1;
   }
 }
 return counted;
}

Excercise 3

Could anyone help me to understand why I am always getting 0 as an answer?
It must be something small that I can’t see easily (I hope there is a debugger in Javascript and you will tell us later @ivan @filip lol

  function countBs (string, char){
    var num = 0;
    var len = string.lenght;

    for (count=0; count < len; count++){
        newChar = string[count];
        if (newChar == char) {
          num++;
        }
    }
    return num;
  }

  var value = countBs("ABCDEFGBT", "B");
  alert (value);
1 Like

This also happens to me time to time :laughing:

You have misspell length

 var len = string.lenght;

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

1 Like
  1. function min(a, b) {
    if (a < b) return a;
    else return b;
    }

    console.log(min(5, 10));
    console.log(min(0, 5));
    in first case it returns 5, in second 0

  2. function isEven(n) {

    if (n>=0)
    if (n==0)
    return true;
    else if (n==1)
    return false;
    else return (isEven(n-2));

    console.log(“Not a positive, whole number”);
    }

console.log (isEven(50)); ----> true
console.log (isEven(75)); ----> false
console.log (isEven(-1)); ----> Not a positive, whole number

function countChar(word, char) {

let count = 0;
for (var i = 0; i < word.length; i++) {
	if(char == word[i]) count++;
}
return count;

}
console.log(countChar(“berseker”, “r”)); ----- 2

1 Like

Haha I knew it would be something like this, js compiler is way too forgiving.
it works now

I’ve created a webpage with all of the exercises solved, you can find it here: LINK

Here is the full code:

<head>
  <title>Javascript, Chapter 3</title>
</head>

<body>
  <h1>Exercise 1: find minimum number</h1>
  <input type="number" id="valueA" name="valueA" value="0">
  <label for="valueA">First number</label><p></p>
  <input type="number" id="valueB" name="valueB" value="1">
  <label for="valueB">Second number</label>
  <p id="ex1_output"></p>
  <br>

  <h1>Exercise 2: check if number is even (with recursive function)</h1>
  <input type="number" id="valueToTest" name="valueToTest" value="50">
  <label for="valueToTest">Number to test</label><p></p>
  <p id="ex2_output"></p>
  <br>

  <h1>Exercise 3: bean count</h1>
  <input type="text" id="inputString" name="inputString" value="Beans are plant foods known as legumes. Commonly consumed beans include kidney beans, navy beans, soybeans, and chickpeas.">
  <label for="inputString">String to test</label><p></p>
  <input type="text" id="inputChar" name="inputChar" value="b">
  <label for="inputChar">Character to count</label><p></p>
  <p id="ex3_output"></p>
  <br>

  <script type="text/javascript">
    ////////////////////////////
    // JS code for exercise 1//
    ///////////////////////////

    //This is the actual function required by the exercise
    const min = (a,b) => {
      if(a>b){return b;}
      else{return a;}
    };

    //Function to be executed when values change
    const buildOutput = function(inputA, inputB, output){
      let valueA = inputA.value;
      let valueB = inputB.value;
      let result=min(valueA,valueB);
      let outHTML="<h3>The smaller number between "+String(valueA)+" and "+String(valueB)+" is: "+String(result)+"</h3>";
      output.innerHTML = outHTML;
    };

    //Fetch items
    let inputItemA=document.getElementById("valueA");
    let inputItemB=document.getElementById("valueB");
    let outputItem=document.getElementById("ex1_output");

    //Event listeners
    buildOutput(inputItemA, inputItemB, outputItem);
    inputItemA.addEventListener('change', function(){buildOutput(inputItemA, inputItemB, outputItem);});
    inputItemB.addEventListener('change', function(){buildOutput(inputItemA, inputItemB, outputItem);});


    ////////////////////////////
    // JS code for exercise 2//
    ///////////////////////////

    //This is the actual function required by the exercise
    function isEven(value){
      //If negative, make positive
      if(value<0){value*=-1;}
      //Return conditions
      if(value==0){return 'even';}
      else if(value==1){return 'odd';}
      else{
        //perform recursive check
        value-=2;
        return isEven(value);
      }
    }

    //Function to be executed when values change
    const buildEvenOutput = function(input, output){
      let result=isEven(input.value);
      let outHTML="<h3>The number is: "+result+"</h3>";
      output.innerHTML = outHTML;
    }

    //Fetch items
    let evenInputItem=document.getElementById("valueToTest");
    let evenOutputItem=document.getElementById("ex2_output");

    //Event listeners
    buildEvenOutput(evenInputItem, evenOutputItem);
    evenInputItem.addEventListener('change', function(){buildEvenOutput(evenInputItem, evenOutputItem);});


    ////////////////////////////
    // JS code for exercise 3//
    ///////////////////////////

    //This is the actual function required by the exercise
    function countChar(string, char){
      let count = 0;
      for(let x=0; x<string.length; x++){
        if(string[x]===char){
          count++;
        }
      }
      return count;
    }

    //Function to be executed when values change
    const buildCountOutput = function(inputString, inputChar, output){
      let result=countChar(inputString.value, inputChar.value);
      let outHTML="<h3>Found: "+String(result)+"</h3>";
      output.innerHTML = outHTML;
    }

    //Fetch items
    let inputStringItem=document.getElementById("inputString");
    let inputCharItem=document.getElementById("inputChar");
    let countOutputItem=document.getElementById("ex3_output");

    //Event listeners
    buildCountOutput(inputStringItem, inputCharItem, countOutputItem);
    inputStringItem.addEventListener('change', function(){buildCountOutput(inputStringItem, inputCharItem, countOutputItem);});
    inputCharItem.addEventListener('change', function(){buildCountOutput(inputStringItem, inputCharItem, countOutputItem);});

  </script>
</body>

1 Like

Nice job! adding your own frontend panel for the exercises is an amazing idea!

I only found one error with the Exercise 1 minimum function:
image

I remember to face something like this before, maybe if you convert the inputA and inputB to integers will do the trick, because the value is being taken has string.

Carlos Z.

//Here is exercise number 1
function findtheminimum(num1, num2){
return Math.min(num1, num2);
console.log(findtheminimum);
}
findtheminimum(200, 100);

//Here is exercise number 1
function isEven(testNumber){
if ((testNumber % 2) === 0){
console.log(“It’s even!”);
}
if (testNumber < 0){
console.log(“Let’s stay positive, please”);
}
if ((testNumber % 2) === 1){
console.log(“It’s odd!”);
}
}
let testNumber = window.prompt(“Enter the number”);
isEven(testNumber);

//Here is exercise number 3
function countBs(tester){
let stringLength = tester.length;
let numberOfLetters = 0;

        for (let counter = 0; counter<stringLength; counter++){
            if (tester[counter] == "B"){
                numberOfLetters = (numberOfLetters + 1);}
            }
 return numberOfLetters
console.log(numberOfLetters);

}

countBs();

function countBs(tester){
let stringLength = tester.length;
let numberOfLetters = 0;

        for (let counter = 0; counter<stringLength; counter++){
            if (tester[counter] == target){
                numberOfLetters = (numberOfLetters + 1);}
            }
 return numberOfLetters
console.log(numberOfLetters);

}
var tester = prompt(“Enter a word or phrase”);
var target = prompt(“Enter the character to count”);
countBs(tester);

Thanks for pointing out this bug! To be honest I didn’t test the function long enough to notice it.

So apparently document.getElementById().value returns a string even if the HTML element is flagged as a number?

I have now updated the code with Number(a)<Number(b) as conditional statement, everything seems to work.

Thanks again :slightly_smiling_face:

I’m lost. Especially the last exercise.

1 Like

Hi @Julie66, hope you are ok.

Could you please your code so we can review it to help you solve it ?

You can use the “Preformatted Text” Button to encapsulate any kind of code you want to show.


function formatText(){

let words = “I’m a preformatted Text box, Please use me wisely!”

}

prefromatted_text-animated

Carlos Z.

Hi @Julie66, hope you are ok.

Could you please your code so we can review it to help you solve it ?

You can use the “Preformatted Text” Button to encapsulate any kind of code you want to show.


function formatText(){

let words = “I’m a preformatted Text box, Please use me wisely!”

}

prefromatted_text-animated

Carlos Z.