Chapter 4 - Exercises

<head>"Sum of a Range"
<title>dynamic list</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head>

<body>
	

  <script>
		var range = function(start, end){
				var arr = [];
					cnt = start;

			while (cnt <= end){
				arr.push(cnt);
				cnt++;
			}
			return arr;
		};

		var sum = function(arr) {
			var total = 0;

			while(arr.length > 0){
				total = total + arr.pop();
			}
		return total;	
		};


			var sum2 = function(arr){
			var total = 0;

			for(let i = 0; i < arr.length; i++){
				total = total + arr[i];
			}
		return total;	
		};


			console.log(sum(range(1, 10)));
			console.log(sum2(range(1, 10)));

  </script>

</body>
``` type or paste code here ```
1 Like

//I hope that is the way, Malik… cheers.

<!DOCTYPE html>

<html>

	<head>"Range and Sum"
	<title>dynamic list</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script></head>

	<body>
		

      <script>
			
      	function ReverseArray(array){
		    newArray = [];
		    length = array.length;
		    for(counter = 0; counter < length; counter++){
		      newArray[counter] = array[length - counter -1];
		    }
		    return newArray;
		  }

var testArray = [12,23,34,45,56,67,78,89,90,101];

console.log(ReverseArray(testArray));


      </script>

    </body>


	


</html>
1 Like

Hello, I’ve done this in ā€œThe sum of a rangeā€ for now but don’t really know how I should continue now. What do I need to do next? I also don’t understand why the array that is used has to be empty? (let arr = [];)
Why is the result of console.log(sum(range(1, 10))) 55? I don’t understand what happens in the sum function.
Thanks in advance!

function range(start, end) {

      let arr = [];
      for(cnt = start; cnt <= end; cnt++) 
      arr.push(cnt);

      return arr;
    }

    function sum(arr) {
      let total = 0;
      for(let value of arr) {
        total += value;
      }
      return total;
    }
    
    console.log(sum(range(1, 10)))
1 Like

The Sum of A Range


function range(c, d, k) {
  var a = [c]; 
  	var b = k ? k : 1; 

  	var i = c;

  while(i != d){
    i += b;
  
    a.push(i); 
  }
  
  return a;
}


function sum(arr) {
  var a = 0;
  	for(var t in arr) {
    a += arr[t];
  }
  
  	return a;
}

Reversing An Array

function reverseArray(arr){
  var a = [];
  	for(var n = arr.length - 1; n >= 0; n--){
    a.push(arr[n]);
  }
  
  	return a;
}
1 Like

Hey @kmilo_Mart,

The reason why your console.log() isn’t logging anything is because a return statement (as well as returning a value) causes the function to be exited, and control flow is passed to wherever the function was called. You can get round this by placing your console.log() BEFORE the return statement.

However, in this particular case, it looks like you want to log each number in the range as it’s generated by the for loop. In order for i to be accessed and logged, you need to place console.log(i) within the for loop, because the variable i has been declared within that local scope and so can only be accessed from there.

Once you do that, you will have 2 statements within your for loop, so you will need to place them within curly brackets.

You also need to remove the semi colon at the end of your for loop header.

Another issue with your code as it is at the moment is the location of the return statement outside of the function. You need to place it at the end of the function but still within its body in order for it to be able to return the array generated by the function.

That’s a very good idea :ok_hand:

I hope the above helps. Just let me know if you need any further pointers :smiley:

3 Likes

Hi @Markus_Bielaszka,
You’ve got two questions in this post. Let’s address it one by one.

First,

This is a good way of instantiating variables before using them in our code. You can imagine as if you are picking up an empty bowl so that you can add stuff to it. By doing let arr = [];, you are basically picking up an empty bowl.
Now, to fill this bowl with various things or to keep it empty is up to you. And that’s what we do in the follow up code later.

Second,

In the sum function, we take the array (filled with different numbers) as input and pick the numbers one by one and keep adding them until we get the final result. Thus, if you add all the numbers from 1 to 10, you result with 55.

The above basically does this in these steps–

  1. range(1,10) --> makes an array with numbers between 1 to 10. //1,2,3,4,5,6,7,8,9,10
  2. sum takes this array with all the numbers and adds them one by one.
  3. console.log shows the output from sum()

Hope this clears your doubt.

Happy Learning. :slight_smile:

2 Likes

Ok thank you very much! I understand now with the empty array! But what I mean is that I don’t understand what all of this is doing:

function sum(arr) {
      let total = 0;
      for(let value of arr) {
        total += value;
      }
      return total;
    }

Sorry if I am asking so many questions but, I am just a bit confused.

function sum(arr) {
      // declare a variable total to compute the total
      let total = 0;
      // loop through all the items in the array, in each loop assign the item to variable "value" 
      // The loop can also be written as 
      // for (var index =0 ; index < arr.length ; index ++) {
      //     total = total + arr[index];
      // }
      for(let value of arr) {
        // pick the item and add it to "total". can also be written as total = total + value
        total += value;
      }
      // after adding all the values return the total
      return total;
    }

Hope this clears it out. Feel free to ask as many questions as possible. That is the only way we can learn better :smiley:

Happy Learning! Cheers!

2 Likes

Ok thanks for the help @Malik ! I will try my best with what you gave me :smiley:

1 Like

The sum of a range:

function range(start, end) {
   var array = [];
   for (var i = start; i <= end; i++) {
      array.push(i);
   }
   return array;
}

function sum(array) {
   var sum = 0;
   for (var i = 0; i < array.length; i++) {
      sum += array[i];
   }
   return sum;
}

function range(start, end, step = 1) {
   var array = [];
   for (var i = start; step < 0 ? i >= end : i <= end; i += step) {
      array.push(i);
   }
   return array;
}

Reversing an array:

function reverseArray(array) {
   var reversed = [];
   for (var i = array.length - 1; i >= 0; i--) {
      reversed.push(array[i]);
   }
   return reversed;
}

function reverseArrayInPlace(array) {
   var j = array.length - 1;
   for (var i = 0; i < array.length; i++) {
      var tmp = array[j];
      array[j] = array[i];
      array[i] = tmp;
      j--;
   }
   return array;  
}
1 Like

Thanks for all your support:
But I’m still struggling with trying to console…

Another question that I have is the following:

for (let i = start; i <= end; i++)

How do I know that in this loop the array I wanna create starts from 1 and ends on 10, how do I check this to see what is going on with the loop? That is why I wanna console what I do to see if I’m going straight.

Is there a way where I can check what the code is doing? or is there a manual way to follow everything I’m typing? I mean if I can track it by writing on paper what the code is doing, for example.

Like so:

1 Like

Hi @kmilo_Mart,

You can track this by using console.log(i) within the for loop body. It will work if you make all the changes to your code which I explained in my last email. If console.log(i) isn’t printing out each number in the range from 1 to 10 (one number printed for each loop) then you must still have an error in your code somewhere. Post a copy of your amended code (after making the changes I suggested) and I’ll be able to see exactly where the problem is.

Also include your function call, so I can see that you’ve got that right as well. If you want to produce an array from 1 to 10 then you’ll need:

range(1, 10);

This will pass the value of 1 into the function as the start parameter, and 10 as the end parameter. As you are declaring your iterator variable as  let i = start , your console.log(i) will log 1 for the first loop, 2 for the second loop etc.

To also see the final array returned from your function, you also have to console.log the function call, or its output assigned to a variable i.e.

console.log(range(1, 10));
// or
const output = range(1, 10);
console.log(output);

If you’re having a lot of problems, then it’s really important that you post a complete version of your code, and not just parts of it, so we can get the full picture of what you are trying to execute.

2 Likes

I needed lots of help on the internet for this, but here goes

var a = [1,2,3,4,5,6,7,8,9];
function revse(start){
  
  var b = new Array;

  for(var i=start.length-1; i>=0; i--){
    b.push(start[i]);
    
  }
  
  return b;
  
}

console.log(revse(a)); 
1 Like
function range(start, end) {

      let arr = [];
      for(i = start; i <= end; i++) arr.push(i);

      return arr;
    }

    function sum(arr) {
      let total = 0;
      for(let value of arr) {
        // of iterates over arr
        //let value becomes 1 + 2 + 3...=55 every time "of" creates a loop iterating over arr
        total += value;
        //and total also becomes 1 + 2 + 3...=55
      }
      return total;
    }
    console.log(sum(range(1, 10)))

So at the end let total = 0; becomes 55? is what I commented on the code correct?
Just trying to understand it.

Thanks in advance :smiley:

1 Like

Hi @Markus_Bielaszka, Yes you got it right! One small correction , in the comment below –

Although ā€œtotalā€ gets the final value of 55 , the ā€œvalueā€ is just individual numbers from the array. That means the numbers between 1 to 10. So, an appropriate comment would be

// let value becomes 1, 2, 3, 4.....10 every time "of" creates a loop iterating over arr

Hope this clears it out.

Happy Learning. ! :slight_smile:

2 Likes

Hi @Malik, Ok I see! thank you very much for the explanation, it was very helpful :smiley:

1 Like

Hi!

I need assistance with Exercise #1, The Sum of a Range. This is what I have so far. The second part to my answer does not write the sum of 55 in my console. I have referred to other students’ posts for assistance, but many of their answers are far too complex for me to understand.

Many of these problems are harder than they sound. Looks can definitely be deceiving.

Please help me out the best you can.

function range(start, end){
  let arr = [];
  for (x = start; x <= end; x++) arr.push(x);

  return arr;
}

function sum(arr){
  let numbers = [5, 10, 15, 20];
  return sum(arr);
}
console.log(sum)

Thank you!

P.S. The list of numbers I put in actually has a sum of 50, not 55. Please correct me wherever necessary.

I think that the problem is that you’re not summing your arr in function range. What you are doing is summing you’re array that is called let number = [5, 10, 15, 20]. All the numbers together in let number are equal to 50, that’s why you’re not getting 55. You’re array: arr is empty right now, so you have to define start and end by calling them with console.log console.log(sum(range(1, 10))); to define start and end. You have to console.log both sum and range together. To sum you’re arr in function range with the help of function sum you should do like this: console.log(sum(range(1, 10)));. To use the argument of function sum(arr) console.log(sum(range())) range() should be the argument of function sum(arr).

hope it helps, sorry couldn’t help you more but, I did my best. :+1:

1 Like

The sum of a range

function range(start, end, step = start < end ? 1 : -1) {
// if "start" is defined as less then "end" then it's true so step = 1
// if "start" is defined as greater then "end" then it's false so step = -1
      let arr = [];

      if(step > 0) {
        for(i = start; i <= end; i += step) arr.push(i);
      } else {
        for(i = start; i >= end; i += step) arr.push(i);
      }
      return arr;
    }

    function sum(arr) {
      let total = 0;

      for(let value of arr) {
        // of iterates over arr
        //let value becomes 1, 2, 3, 4.....10 every time "of" creates a loop iterating over arr
        total += value;
        //and total also becomes 1 + 2 + 3...=55
      }
      return total;
    }

    console.log(sum(range(1, 10)));
    console.log(range(1, 10, 2));
    console.log(range(5, 2, -1));
1 Like

Okay. I’ll see how this works out.

Thank you!

1 Like