Chapter 4 - Exercises

Hi Cristian,

Yes, you’re doing the right thing. If you just copy and paste you won’t actually be learning.

You’ve got the console.log() in the right place in your code now. Hopefully, you can now see why your previous version wasn’t giving you the output of each iteration of the for loop, which is what you wanted to check that your array of the range is being generated correctly. So, now, when you run your code you will see that the range your code is generating is correct based on the start and end parameters. In order to check that the returned array is also correct and complete you need to add a function call and log that to the console too:

console.log(range(1, 10));
/* test with different start and end arguments */

If you want to log the state of the array at the end of each loop (instead of just the individual number added to it), then you need:

console.log(arr);
// instead of
console.log(i);

Once you’ve done this and understand how it works, you’re ready to move on to the next stages:

  1. Add the sum() function, which calculates the sum of all of the numbers in the array generated by your first function. In the exercise instructions, the sum function is called with the range function as the argument:
console.log(sum(range(1, 10)));

This means that your array of the range will be passed into your sum() function, where you can write code that iterates over each number in the range, adding it to a cumulative total.
Again, you can check that this cumulative calculation is being performed correctly by including an additional console.log within your for loop, which logs the variable storing your cumulative total at the end of each loop.

All of the remaining stages only require additions and modifications to your range() function. You don’t need to make any further changes to your sum() function, as it will always sum the numbers included in whatever array is produced and passed to it.
2. Add a 3rd parameter to your range() function called step, which sets the interval between each number in the range.
3. Add additional functionality to your range() function, so that it can generate descending ranges as well as ascending ones. Descending ranges should be generated when start > end.
4. The final part is then to add a default for the step parameter, so that when the step parameter is omitted (i.e. left undefined) it will default to either 1 (for ascending ranges) or -1 (for descending ranges).

Don’t forget that for a bit of extra help (without actually being given the solution) you have the hints, which you can display in the online course book by clicking below the exercise instructions.

Good luck! If you want to check your progress at different stages, then post your full code here, and we’ll take a look at it. If you have any specific questions about a particular part of your code that you’re having problems with, then explain that in your post as well :slightly_smiling_face:

And don’t worry at all if it takes you time to reply. We understand totally that everyone has busy lives and other commitments.

4 Likes
 var start = 1;
       var end = 10;

       var numRange = [];
       for (var i = start; i <= end; i++){
         numRange.push(i);
       }
       var sum = numRange.reduce(function(a,b){
         return a + b;
       }, 0);

       console.log(numRange);
       console.log(sum);

       function reverseArray(numRange){
       var newNumRange = [];
       for(var i = numRange.length - 1; i >= 0; i--){
         newNumRange.push(numRange[i]);
         //console.log(newNumRange);
       }
         return newNumRange;

       }
console.log(reverseArray(numRange));
1 Like
THE SUM OF A RANGE

// range function
function range( start, end, increment ) {

  // create the result array
  var result = [];

  // test to see if we have an increment, otherwise set it to 1
  if ( increment == undefined )
    increment = 1;

  // calculate the number of times to loop (this is because you might be going
  // up or down with your increment)
  numLoops = Math.abs( (end - start)/ increment ) + 1 ;

  // loop that many times
  for ( var i = 0; i < numLoops; i ++ ) {

    // add (push) the value of start to the array
	result.push( start );

    // increment the value of start
    start += increment;
  }

  // return the array with all the things in it
  return result;
}

function sum( numArray ) {
  // set a variable to hold the sum
  var arrayTotal = 0;

  // see how many numbers are in the array
  numLoops = numArray.length;

  // loop that many times
  for ( var i = 0; i < numLoops; i ++ ) {
    // add the number at that index to the sum
    arrayTotal += numArray[i];
  }
  // return the sum
  return arrayTotal;
};

console.log(range(1, 10));
// → [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(range(5, 2, -1));
// → [5, 4, 3, 2]
console.log(sum(range(1, 10)));
// → 55

REVERSING AN ARRAY

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();

console.log(fruits);
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function reverseArrayInPlace(fruits) {
    for (var i = 0; i<fruits.length/2; i++) {
      var temp = fruits[i];
      fruits[i] = fruits[fruits.length -1 -i];
      fruits[fruits.length -1 -i] = temp;
      
        
    }
    return fruits;
    
};


console.log(reverseArrayInPlace(fruits));
  

`

1 Like
function range (start,end,step) {
  step = step || 1;
  let arr = [];
  for (arr;(end-start)*step>=0;start += step) {
    arr.push(start);
  }
  return arr;
}

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

console.log(sum(range(1,10)));
1 Like
function reverseArray(array) {
  let output = [];
  for ( let i = array.length -1; i>=0; i--){
    output.push(array[i]);
  }
  return output;
}
console.log(reverseArray([2,4,6,8,10]));

function reverseArrayInPlace(array) {
  for (let i=0; i<Math.floor(array.length/2);i++) {
    let old = array[i]; // assigining a varaible to a fixed value for later use in (part 2)
    array[i] = array [array.length -1-i]; //first #element in array is assigned to last #element in array
    array [array.length -1-i]= old; //last #element is assigned to first #element of array (part 2)
  }
  return array;
}

let arrayValue = [1, 2, 3, 4, 5];
console.log(reverseArrayInPlace(arrayValue));
1 Like

Things are taking time to sink in… still getting syntax incorrect which is then taking ages to spot.
It’s all part of the learning process…
I have had to use lots of resources to work this out and I had several versions as I tried to either work out what was going on in examples as I studied them or as I was working out what I’d done!

SUM OF RANGE

Part One

function range(start,end){  //create the function with the arguments start and end
    var array = []; // create an array
    //generate a loop, calculate the value, add it to the array
    for (i=start; i<=end; i++){  // for loop with start and end add 1 each loop
      array.push(i); // push number to the array - it adds it to the end of the array
    }
    return array; // one return statement per function
  }
  console.log(range(1,10)); 
//Output gives:
//>(10) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

PART TWO

This is the first way I worked out to do it:
function sum(array) {
    var sum = 0; //variable sum is set to zero initially
    for (let value of array) { // for/of loops through the values (value) of an iterable object (array)
      sum += value;  //this adds the value of each element to the sum as it loops
    }
    return sum; //returns the sum of the array elements from the function
  }
//Output for first version of sum
//>55

but I also found this way as well…

function sum(array) {
  var sum =0;
  for(let i=0; i<array.length; i++) {   //for loop using array length as the limit
    sum += array[i];
    }
    return sum;
  }
//OUTPUT for second version of sum
//>55

which meant that I could do the next bit…

console.log(sum(range(1,10)));
//Output
//>55

BONUS PART

In hindsight, it would have been easier to keep copies of the file with the above code in it and cut and paste from there... what I decided to do was to rewrite the code lower down the page and use a series of comments to mark code active or not... always remember KISS... So after hours and days... I think this is what I finally came up with after lots of research, lots of head scratching... lots of unpicking what others had done to make sure that I really understood what was going on. I'm leaving loads of comments in here and lots of test cases so you can see what I was trying to do... many of my mistakes were basic errors, like having the return array statement in between the wrong set of {}...

function range(start, end, step = start < end ? 1 : -1){  //function with 3 arguements
  // the step argument uses conditional operator  condition ? iftrue : iffalse
  // so if start is less than end step = 1, if start is greater than end use  use step = -1
  // example s1 < e10 use 1, s0 < e0 use -1, s10 < e1, use -1
  // using conditional operator means you reduce to two options, in inner loop.
  var array = [];  
  //console.log ("Step value before we go into the IF statement is " + step);
  if (step > 0 ) {  // you use the outcome for true (ie 1)
    //console.log("Value of step in the IF statement at this point is  " + step);
    for (var i=start; i<=end; i += step)  {
      array.push(i);
      //console.log("Start \(" + start + "\) is less than end \("+ end + "\) and step \(" + step + "\) is greater than 0  ");
    }
  }
  else {  //you use the outcome for false and step is <=0
    if (step == 0) console.log("Step is set to zero and will not work  " + step);
    for (var i = start; i >= end; i += step)  {
      array.push(i);
      //console.log("Else statement triggered  " + start + "  " + "  " + end + "  " + step);
      //console.log("array length   " + z);
    }
  }
  return array;
}

function sum(array) {
  var sum = 0;
  for (let value of array) { // for/of loops through the values (value) of an iterable object (array)
    sum += value;  //this adds the value of each element to the sum as it loops
  }
  return sum; //returns the sum of the array elements from the function
}

//TEST CASES
//console.log(range(1,10,2) +  "  T1");  //Test case, start less than end, step greater than 0
//console.log(range(1,10,0.5) + "  T2"); //Test case, start less than end, step greater than 0, less than 1
//console.log(range(1,3) + "  T3");  //Test case, start less than end, no step, no step, should default to step = 1
//console.log(range(3,1) + "  T4"); //Test case, start greater than end, no step, so step set to -1 triggers Else clause/console.log(range(1,3,-1) + "  T5"); // negative step, start less than end
//console.log(range(1,8,0) + "  T5"); // negative step with start less than end
//console.log(range(5,2,-1) + "  T6" ); // negative step with start greater than end

//console.log(sum(range(1,10,2)) +  "  T1");  //Test case, start less than end, step greater than 0
//console.log(sum(range(1,10,0.5)) + "  T2"); //Test case, start less than end, step greater than 0, less than 1
//console.log(sum(range(1,3)) + "  T3");  //Test case, start less than end, no step, no step, should default to step = 1
//console.log(sum(range(3,1)) + "  T4"); //Test case, start greater than end, no step, so step set to -1 triggers Else clause/console.log(range(1,3,-1) + "  T5"); // negative step, start less than end
//console.log(sum(range(1,8,0)) + "  T5"); // negative step with start less than end
//console.log(sum(range(5,2,-1)) + "  T6" ); // negative step with start greater than end

//OUTPUTS
console.log(range(1,10,2));
//> (5) [1, 3, 5, 7,9]
console.log(range(5,2,-1));
//>(4) [5, 4, 3, 2]
console.log(sum(range(1,10,2)));
//> 25

I’ve spent so much time commenting and uncommenting to try and get it to work, that I apologize in advance if anyone spots any issues, but I’m at the point where I can’t look at it any more…

Right off to try the next exercise…

1 Like

1 Like

I found this exercise so much easier than the Sum of Ranges, may have been fresh coffee!

Reverse Array

function reverseArray (array) {
  var arrayOutput = []; //define  array variable for result
  for (let i = array.length -1; i >= 0; i--) {
    arrayOutput.push(array[i]);
  }
  return arrayOutput;
}
console.log(reverseArray([1,2,3,4]));
// OUTPUT >(4) [4, 3, 2, 1]
console.log(reverseArray(["Tom", "Dick", "Harry", "Test"]));
//OUTPUT > (4) ["Test","Harry", "Dick", "Tom"]

Reverse Array In Place

This has some some comments in it to explain my logic as I went through. Only bit I needed some guidance on was Math.floor.

function reverseArrayInPlace (array) {
  for (let i = 0; i < Math.floor(array.length / 2) ; i++) {  // work 50% of the array length, Math.floor rounds DOWN to integer
    let hold = array[i];  // holds the value of the array element before you overwrite it
    array[i] = array [array.length -1 - i];  //(array.length-1) gives element id, as i increases you work closer to the array centre, swapping the values
    //eg [1,2,3,4] > 1st iteration, array[0]=array[4-1-0], array[0]=array[3], ie array[0]=4
    //that's why you need the variable to hold the original i value
    //at this point in the first iteration the array is [4,2,3,4]
    array[array.length - 1 - i] = hold; // this put the original value in it's new location in the array
  }
return array;
}
console.log(reverseArrayInPlace([1,2,3,4]));
//OUTPUT> (4) [4, 3, 2, 1]
console.log(reverseArrayInPlace(["Tom", "Dick", "Harry", "Test"]));
//OUTPUT> (4) ["Test", "Harry", "Dick", "Tom"]
1 Like

Please feel free to correct me if Im wrong.

The Sum of a Range

var numbers = [];

function range(x,y,z) {
  if (z > 0) {
  for(var counter = x; counter <= y; counter= counter + z) {
    numbers.push(counter);
  }
 } else if (z < 0) {
    for (var counter = x; counter >= y; counter = counter + z) {
      numbers.push(counter);
      }
} else {
  for (var counter = x; counter <= y; counter++) {
    numbers.push(counter);
    }
  }
};
range(5, 2, -1);

console.log(numbers);

var total = 0;
function sum() {

  for (var counter = 0; counter < numbers.length; counter++) {
    total = total + numbers[counter];
  };
};
sum();

console.log(total);

Reversing an Array:

var numbers = [1, 2, 3, 4, 5, 11, 12, 13, 14, 15];

function reverseArray(numbers) {
  let newArray = [];
  for (var i = numbers.length-1; i >= 0; i--) {
    newArray.push(numbers[i]);
  };
  console.log(newArray);
};
reverseArray(numbers);

function reverseArrayInOrder(numbers) {
  for (var i = 0; i < numbers.length; i++) {
    var placeholder = numbers[i];
    numbers[i] = numbers[numbers.length-1-i];
    numbers[numbers.length-1-i] = placeholder;
  };
  console.log(numbers);
};
reverseArrayInOrder(numbers);

2 Likes

All of it works, just wanted to thank you for bringing into my attention a problem I had with my code, as I didn’t build my condition on the basis of the 3rd argument being positive or negative. So I needed to make sure that the step was positive or negative when it needed to:

Mod your range function to:
- Take an optional 3rd arg that indicates
the step value used when building the array
- If no step is given, elements go up in +1
*/


let rangeMod = (start, end, step = 1) =>{
  let arr=[];
  if(start>end){
    -Math.abs(step);
    for (var i = start; i >= end; i += step){
      arr.push(i);
    }
  }
  else{
    Math.abs(step);
    for (var i = start; i <= end; i += step) {
      arr.push(i);
    }
  }
  return arr;
}

About the other exercise, you have to carefully read the instructions. If I got it right, the first function should return a new array with the numbers reversed, and leave the original array as it was, while the second function should not return a new array, but modify the value of the array you’re feeding it. That is the difference between a function that returns a value and a function that creates a side effect.
Here’s how I did it:


/*
Write a function that
- Takes an array as an argument
- Produces a new array with the same elements in inverse order
*/

let reverseArray = arr =>{

  let arrev = [];                  //Create new array to be returned
  for (let elem of arr){           //Place each element of the original at the beginning of the new 
                                   //array
    arrev.unshift(elem);           
  }
  return arrev;                    //Return the new array
}


/*
Write a function that
- Takes an array as an argument
- MODIFIES the array reversing its arguments
*/

let reverseArrayInPlace = arr =>{
  let arrev = [];                      //placeholder array
  for (let elem of arr){
    arrev.unshift(elem)                //Fill the placehoder with the values reversed
  }
  arr.length = 0;                      //Empty the values of the original array   
  arr.push.apply(arr, arrev);         // Copy the reversed values to the original array
}

I also did the exercises related to Objects. I really recommend you to do them if you want to really understand objects, and likely lose a little bit of your sanity.

3 Likes

I’ve attached my solution as an image file. I managed to get it to spit out the array properly even without the 3rd argument (step). BUT, i can’t seem to get it to order the numbers from high to low when the arguments are something like range(5,2). Even range(5,2,-1) produces array [2,3,4,5] instead of [5,4,3,2]. Tried messing with start and end values assigned to the i variable, but it still for some reason always spits out the array from low to high numbers. Maybe somehow could use unshift or somethin?

  1. Sum of a range

  2. Reversing Array

1 Like

Amazing. I Just need to understand how to write it on my own…

  1. SUM OF RANGE -
 <script>

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

      function sum(numbers){
        result = 0;
        for (let num of numbers) {
          result += num;
        }
        return result;
      }

      document.write(sum(range(1, 10)));

    </script>

This is an answer if finally had to work out by using other peoples methods and trying to gather together in to my own. Its been really tough and im just wondering how to convert this to reverse?

Is there any help you could do on this @Malik

I had to go back to the start of the course and work on some basic stuff again. Wish was really refreshing i may add.

I am happy ive done it.

Rob.

1 Like

Exactly. If you use unshift, you’ll end up with the first element you put in the array at the last position.

I’ve since looked at the book’s solution, and they used a conditional operator on the step argument…i had no idea i could make modifications to the arguments in that portion of the code. so much cleaner

1 Like

my solutions for array reversal exercise. The top one I did myself…the “in place” one i found on some website…i don’t think i would have come up with that. One thing I am wondering about though - what’s the relation of these two functions to the discussion in the exercise about side effects and pure functions? Is the “in place” one a pure function? What is the side effect of the other one?

Sum of Range:

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

    function sum(array) {
        var tot = 0;
        for (n in array) {
           tot +=array[n];
        }
        return tot;
    }

    console.log(range(1, 10, 2));
    console.log("Sum of array is: "+sum(range(1, 10, 2)));

Reversing Array:

function reverseArray(inArray)
      {
        let count = inArray.length - 1;
        let outArray = [inArray[count]];

		      for (let i = count; i > 0; i--)
		{
			outArray.push(inArray[i-1]);
		}

		return outArray;
	}

	console.log(reverseArray([0,2,4,8,16,32]));
1 Like

I’m totally stuck and need help solving the problem. This had dragged me down for weeks(!) as nothing worked, which was frustrating. I find the problem more complicated than what had been taught, and beyond what I had learned and could follow up to this point. Neither reviewing the lessons helped clarify to go about doing the exercises on my own. I resorted to randomly choosing and copying a number of solutions submitted here in the forum but that only got me even more confused, especially after finding out that most of the programs did not even produce the expected, correct results. Ivan in the ad says anybody (even without programming experience) could do it? I’m moving on to the next lesson and shouting out to anyone who could enlighten me while hoping, in the meantime, to gain back the zeal I had when I started this course.

The solution provided seemed simple though I also would not have dealt with it the same way: three problems solved in one short program. I saw it as 3 separate programs, with each being challenging enough!

3 Likes

// I looked these answers up - the best I could do for now.

//The sum of a range

  function range(start, end, step = start < end ? 1 : -1) {
  let array = [];

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

//The sum of a range Bonus

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

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

//Reversing an Array

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

function reverseArrayInPlace(array) {
  for (let i = 0; i < Math.floor(array.length / 2); i++) {
    let old = array[i];
    array[i] = array[array.length - 1 - i];
    array[array.length - 1 - i] = old;
  }
  return array;
}

console.log(reverseArray(["A", "B", "C"]));
let arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
1 Like