Chapter 3 Exercises

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

function countBs(string){
  return countChar(string, "B");
}
1 Like

FUNCTION 1

   function min(a,b){
    if(a<b){
      document.write(a + " is smaller the smaller value!");

    }

    else if(a>b){
        document.write(b + " is the smaller value!");


    }

    else {
      document.write("You entered the same values.");
    }

  }

  document.write(min(3,5));

// Can anyone tell me why I get an “Undefined” after my the document.write(min(3,5); ? Thanks

1 Like
//MININUM EXCERCISE

// If we NOT use Math.min then this will be a way:

function give(b,t){
  if(b<t){
    return b;}
    else{
      return t;}
      }

      var answer = give(1,2);
      alert(answer)

//**Give me 1 BTC**
//Recursion EXCERCISE

function isEven(n){
  if (n==0) {
  return true
// the function is calling itself until its true
}

else if (n==1) {
  return false
// the function is calling itself until its false
}

else if (n <=-1) {
  return isEven(-n)
}

else
return isEven(n-2);
}


console.log(isEven(50));
// true firstcoding.html:33 
console.log(isEven(75));
// false firstcoding.html:35
console.log(isEven(-1));
// false firstcoding.html:37
console.log(isEven(-50));
// true firstcoding.html:39
console.log(isEven(-75));
// false firstcoding.html:41
// BEAN Counting EXCERCISE | this excercise was a bit harder | Youtube is amazing.

function countChar(string, figure){
result = 0;
for (i = 0; i < string.length; i++){
if (string[i] === figure){
result = result + 1;
}
}
return result;
}
document.write(countChar("bebebaby", "B"));```
1 Like

Good solutions @qh.w,

Did you arrive at the same solutions as the model answers, yourself, before looking? If so, really well done!

Have you had a go at Bean Counting as well? … or is that still a work in progress? :slight_smile:

@daz3d === " :fire: :fire: :fire:"

Great stuff!

That’s soooo important to keep the motivation going!

…maybe a bit too much now? :sweat_smile: (at least how its’s appearing here in your forum post…)

I think you can just remove the cntBs function and pass both prompt outputs directly to the count function, by modifying the final lines of your program in a similar way to my suggestion below…let me know what you think.

I only meant to keep and adapt countBs because that was part of the exercise. The idea of the exercise was to end up being able to either (i) call count directly with parameters for both a word, and a letter to count; or (ii) call countBs with just a word, with the function always counting B’s, but now also calling count (passing in the word and always "B" as the 2nd parameter) to perform the computation.

But don’t worry about it! You’ve already gone way over and above that! :star2:

const myString = prompt("Give me a string to test.");
const char = prompt("What character do you wish to search for in the string?");

const countString = count(myString, char, 0, 0);
document.write("<center>" + countString + "</center>");

Good solutions, @matthurd :+1:

A few observations…

Minimum

You don’t need the second Boolean expression, because if the first Boolean expression evaluates to false then by default b must be the lowest. And, in addition, if you leave the second Boolean expression as it is, if both numbers ( a and b ) are equal, the function will return undefined . So your final solution should look like this:

function min(a, b) {
   if(a < b) return a;
   else return b;         // removed  if(a > b)
}

In addition, you need to actually call the function min by appending parentheses to the function name, and including two numbers as arguments. As your code stands at the moment you are logging the actual function to the console, instead of the value that it returns!

console.log(min(0, -20));    // => -20

Recursion / Bean Counting

Did you arrive at the same solutions as the model answers, yourself, before looking? If so, really well done!

Unfortunately, the code you’ve posted for both exercises throws an error, because your Recursion is missing a final curly brace, and your Bean Counting has one curly brace too many! :sweat_smile:

Hi @Long,

Minimum :ok_hand:

The term arguments simply refers to values that are passed into a function when a function is called (or invoked, or executed) as follows:

   min(9, 25);

/* This is a function call, executing the min function
   9 and 25 are both arguments that will be passed into the function.
   In the function they termed parameters, but are still the same values.
   9 and 25 are still values: number values (numeric value types) */

Recursion

Did you arrive at exactly the same solution as the model answer, yourself, before looking? If so, really well done!

Bean Counting

Great, so far :+1:

There is also an additional step to this exercise. Now that you have the second function countChar , which has 2 parameters, can you slim down countBs() so that it still only has one parameter, but calls countChar to do the computation and then still always returns the number of B’s?

//Execise 1

function takingMin (a, b) {

if (a > b) console.log(b)

else console.log(a)

}

takingMin(1, 2)

//Execise 2

function isEven(n) {

if (n == 0) return true;

else if (n == 1) return false;

else if (n < 0) return isEven(-n);

else return isEven(n - 2);

}

//Exercise 3

function countBs (string) {

let total = 0

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

    if (string.charAt(i) === 'B')

    total = total + 1

}

console.log(total)

}

countBs(‘BBBaBBBB’)

function countChar (string, searchStr) {

let total = 0

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

    if (string.charAt(i) === searchStr)

    total = total + 1

}

console.log(total)

}

countChar (“Hiiiiiii”, “H”)

1 Like

// Write a function min that takes two arguments and returns their minimum.
const min = function(numa, numb){
if(numa<numb){
return numa;
}
else{
return numb;
}
};

console.log(min(0, 10));
// → 0
console.log(min(0, -10));
// → -10

//Define a recursive function isEven
const isEven = function(num){
if(num==0)
{
return “true”;
}
else if (num==1)
{
return “false”;
}
else if(num<0)
{
num+=2
return isEven(num);
}
else
{
num-=2
return isEven(num);
}
};
console.log(isEven(50));
// → true
console.log(isEven(75));
// → false
console.log(isEven(-1));
// → false

//Write a function countBs that takes a string as its only argument and returns a number that indicates how many uppercase “B” characters there are in the string.
function countBs(string)
{
let string_length = string.length;
let b_num=0;
for(i=0;i<string_length;i++)
{
if(string[i]==“B”)
{
b_num+=1;
}
}
return b_num;
}
console.log(countBs(“BBC”));
// → 2

1 Like
type or paste code here
```<script>

  function min(x,y){
    if (x < y){
      return x;
    }
    else {
      return y;
    }
  }

document.write(min(69,-69));


  </script>

<script>



  function CountBs(string){
    let amount = 0;
    for(let counter =0; counter < string.length; counter++){
      if(string[counter] == "B"){
        amount++;
      }
    }
    return amount;
  }

  var inputString = prompt("Write me any BS you want and Ill count your capital B's ");

  document.write("<h1> Your sentence has </h1>" + CountBs(inputString) + "<h1> B's</h1>");

  function CountChar(string, char){
    let amount = 0;
    for(let counter =0; counter < string.length; counter++){
      if(string[counter] == char){
        amount++;
      }
    }
    return amount;
  }

  var letter = prompt("Give me the letter you want to count");

  var inputString = prompt("Now give me that sentence you want me to find your letter in");



  document.write("<h1> Your sentence has " + CountChar(inputString, letter) + letter + "'s </h1>");




  </script>


<script>

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


  </script>
1 Like

Hi @laserkavajen ,

Did you manage to arrive at the same solutions as the model answers, by yourself? If so, really well done! :muscle:

How about the second exercise, Recursion? Are you still working on that one, or is there anything you’d like help with?

1 Like

Hi @Junte,

It’s because you are not returning any value from your function. You are writing the output to the document directly from within the function, so the document.write() wrapped around the function call min() doesn’t have any value to process.
So, to stop undefined being displayed, you have 2 options:

  1. Remove the document.write() from the function call, so you just have:
    min(3, 5);

    OR

  1. Replace each of the three document.write() statements within the function, with return statements (and remember to also remove the parentheses). i.e.
    function min(a,b){
       if(a<b){
          return a + " is the smaller value!";
       }
       else if(a>b){
          return b + " is the smaller value!";
       }
       else {
          return "You entered the same values.";
       }
    }  

    document.write(min(3,5));

Option 2 is better in terms of making the program easier to adapt and develop further. This is because the function always returns the result, and so you will always have the flexibility to modify the program to do anything you want with that value. By leaving the function itself to write the result to the document, you are restricting what your function can actually be used for. If you want to change that functionality in the future you will have to make a lot of internal modifications to the function itself; whereas with return statements you avoid having to do that.

Are you still working on the other two exercises, Recursion and Bean Counting? Let us know if you have any more questions or need any help. :slightly_smiling_face:

1 Like

Minimum

function min(a, b) {
return a < b ? a : b;
}

Recursion

function isEven(num) {
if (num < 0) return “Number must be a positive integer!”;
if (num == 0) return “Even”;
if (num == 1) return “Odd”;
return isEven(num - 2);
}

console.log(isEven(-1));

Bean counting

function countBs(s){
return countChar(s, “B”);
}

function countChar(s, c){
let count = 0;
for(var i = 0; i < s.length; i++){
if(s[i] == c) count++;
}
return count;
}

1 Like

MINIMUM

function min(a,b){
var a; var b; var result;
if(a<b){result=document.write(“minimum is”+" “+a);}
else{result=document.write(“minimum is”+” "+b);}
return result;
}
min(12,39);

RECURSION

function isEven(N){
if(N<=1){if (N==0){return true;}
else{return false;}
}
else{return isEven(N-2);}
}
console.log(isEven(50));
console.log(isEven(75));
console.log(isEven(-1));

1 Like

Thanks for your help Jon!

Yes I am still working on them, I should have them ready soon =)

1 Like

Great coding, @Omar!
You seem to be flying now! :muscle:

You’re adding some really good comments to your code too, which shows you’re really thinking about what’s actually happening :ok_hand:

By the way, there was a final part to the Bean Counting exercise. Can you slim down your original countBs function so that it still takes just one parameter (the word or string) but then calls countChar() to always count the number of B’s, but still returning the output itself?

1 Like

Function 2

  function isEven(n){
    if(n==0){
      return true;
    }

    else if(n==1){
      return false;
    }

    else if(n<0){
      return isEven(-n);
    }

    else {
      return isEven(n-2);
    }
  }

  document.write(isEven(50));
  document.write(isEven(75));
  document.write(isEven(-1));
  document.write(isEven(-10));
1 Like

Hi @Li_Sun,

Good solutions :ok_hand:

By the way, there’s a final part to the Bean Counting exercise. Can you slim down your countBs function so that it still takes just one parameter (the string) but then calls countChar() to always count the number of B’s, but still returns the output itself?

Bean Counting, First Part

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

      if(string[i] === 'B'){

        result = result + 1;
      }
    }
    return result;

  }

  document.write(countBs("BBC and CBC"));

  function countChar(string, character){

    let result = 0

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

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

        result = result + 1;
      }
    }
   
    return result;

  }
  document.write("<br>");
  document.write(countChar("Hello my Name is Andrea. Nice to meet you", "e"));

</script>
1 Like

Hi @keithra1948,

Nice solutions :ok_hand:

By the way, there’s another part to the Bean Counting exercise. You need to build another function countChar() which has 2 parameters (string and character), and which can count whichever character is chosen i.e. not just B’s.
Then you need to modify your countBs function so that it still takes just one parameter (the string), but then calls countChar() to always count the number of B’s, while still returning the output itself.
Have a look again at the instructions in the course book for more details.

Also, please format your code when you post it here in the forum. You can click on the </> icon in the menu at the top of this forum text-editor. That will give you 2 sets of 3 back ticks…
```
```
If you now input your code between these, you will end up with it nicely formatted, which is then also easier for you to organise with the correct spacing, indentation, nesting and brackets etc. It also makes your code much easier for others to read, and for us to check it for you. Your code for the first exercise should end up looking something like this:

const min = function(numa, numb) {
   if (numa < numb) {
      return numa;
   }
   else {
      return numb;
   }
};

console.log(min(0, 10));
// → 0
console.log(min(0, -10));
// → -10
1 Like