Chapter 4 - Exercises

Great question @Chakingo!

No, because if the else statement is triggered, that means that start >= end i.e. we have a reverse range. If we have a reverse range then our step parameter must be negative.
So, let’s say we have a step of -2; our final expression in our second for loop header will be…

i += -2   =>   i = i +-2   =>   i = i - 2

So, due to step having a minus sign, mathematically, it effectively converts our += assignment operator into -= , meaning that it keeps pushing a lower number.

However, we can improve the program, because as it is at the moment, if the start parameter > end parameter, then we are reliant on two things always being the case:

  1. A 3rd step parameter must always be introduced ( * see below)
  2. The step parameter must always be negative.

*  With our current step parameter assigned a default of 1, if no step parameter is defined, then it will default to +1 for both ascending and descending ranges. So to prevent this, we need to adapt our code to give a default of either +1 or -1 accordingly.

(@takJohn )

1 Like

Excellent, @rbrownlow! :+1:

Just a small observation about your Reversing an Array (part 2 – “in place”)…

This isn’t returning the reversed array, but instead the last number to be reversed from “front to back” i.e. 2 (using your example) which changes places with 4.
This isn’t a problem when you’re not doing anything with this returned value (which you’re not at the moment — you’re invoking the function and then logging the new reversed version of arrayValue). But if you log the function call…

var arrayValue = [1, 2, 3, 4, 5];
console.log(reverseArrayInPlace(arrayValue));   // => 2

If you intend to return the reversed array, then you need to change…

return current;
// to
return array;

However, I’m mentioning this because it raises an interesting point. If all we want to achieve is the reversal of our original array, then we actually don’t need our function to return any value. If you’ve still got the additional console.log() wrapped around your function call, then remove it; then remove the return statement from the function, and you’ll see what I mean…then have a think about what’s happening :thinking:

Keep on learning! :muscle:

1 Like

Sum of Range & Reverse Array In Place:
I wanted to create an interface for users to get the sum of their own range, and get the reverse array with one click.

<html>

<head>
    <title>Chapter 4 Exercise</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>

<body>

    <h1>Exersice 1: The Sum Of A Range</h1>
    <input type="number" id="start" value="" placeholder="Input Lowest Number" />
    <input type="number" id="end" value="" placeholder="Input Highest Number" />
    <input type="number" id="step" value="" placeholder="Input Step Size Number" />
    <button id="calc">Start SumRange. </button>
    <button id="ReverseArr">Reverse Array </button>

    <p>The list of numbers used in calculation</p>
    <ul id="ordlist"></ul>
    <p>ListNumbers ReverseArrayInPlace:</p><br>
    <ul id="ordListRevIp"></ul><br>

    <p id="sumnum">The Sum Of The Range Is: </p>
    <script>
        function NewArray(a, b, c) {
            let array = []
            let arraylist = $("#ordlist")
            let sum = 0;

            array.length = 0;

            if (Number(c) < 0) {
                for (i = Number(b); i >= Number(a); i = i + Number(c)) {
                    array.push(i);
                    sum += i;
                    $("<li/>").text(i).appendTo(arraylist);
                }
            } else {
                for (i = Number(a); i <= Number(b); i = i + Number(c)) {
                    array.push(i);
                    sum += i
                    $("<li/>").text(i).appendTo(arraylist);
                }

            }
            $("#sumnum").text("The Sum Of The Range Is: " + sum);
            console.log(array)
        };
        $("#calc").click(function() {
            $("#ordlist").html("");
            NewArray($("#start").val(), $("#end").val(), $("#step").val());

        });
    </script>
    <h1>Exercise 2: Reverse Array</h1>
    <p>ReverseArray In Place</p>
    <script>
        var numbers = [];
        var RevNumbers = [];

        function showarray(ar, name) {
           
            $.each(ar, function(i, value) {
                $("#" + name).append("<li>" + value + "</li>");
            });
        };

        
        function MakeArray(a, b, c) {
            numbers.length = 0; 
            
            for (i = Number(a); i <= Number(b); i = i + Number(c)) {
                numbers.push(i);
            }
            showarray(numbers, "ordlist");
        };


       
        function ReverseArrayInPlace(a) {
           
            var temparray = [];
            temparray.length = 0;
            var b = 0;
            for (i = a.length - 1; i >= 0; i--) {
                temparray.push(a[i]);
                b++;
            }
            a.length = 0; 
            for (i = 0; i < temparray.length; i++) {
                a.push(temparray[i]);
            }
            
            showarray(a, "ordListRevIp");
        };


        
        $("#ReverseArr").click(function() {
            $("#ordlist").html("");

            $("#ordListRevIp").html("");
            MakeArray($('#start').val(), $('#end').val(), $('#step').val());

            ReverseArrayInPlace(numbers);
        });
    </script>

Reverse Array:

 <script>
        function reverseArray(list) {

            return list.reverse();
        }
        var rev = ["Ivan", "On", "Tech"]
        document.write("The array is: " + rev + '<br>' + '<br>')

        document.write(" The ouput is  " + reverseArray(rev))
    </script>

Initially, I wanted to create an input box in which the program will split strings/numbers with “,” , and sort them out in an array. This is because I did not want to create a code that will use the inbuilt array.However, I was having such a hard time understanding how an input box can be used to create an array, followed by it reversing the order.

So far I have manage to create an input box that adds the strings to an array, as shown below.(This is what I could find online, the ReverseArray is what I was testing with the code. No luck :confused:)

<table>
            <tr>
                <td>Enter the Input</td>
                <td><input type="text" id="inputtext" /></td>
            </tr>
            <tr>
                <td></td>
                <td><button type="button" id="add" onclick="addRecord();">Add </button>
                <button type="button" id="display" onclick="displayRecord();">Display</button>
                </td>
            </tr>
    </table>

   <div id='values'></div>
    <script>
        var values = []

        function addRecord() {
            var inp = document.getElementById('inputtext');
            values.push(inp.value);
            inp.value = " ";
            document.getElementById("values").innerHTML = values.join(", ");



        }

        function reverseArray(list) {

            return list.reverse();


        }
        var list = document.getElementById('inputtext').value;

        document.write(" The output is  " + reverseArray(list))

PS: Thank you to the form and the internet, I don’t know how I would have been able to accomplish what I wanted without their help :heartpulse:

1 Like

Why do I get Uncaught TypeError: Cannot read property ‘length’ of undefined
at arrays2.html:25

function range(start, end){
var c = [];
for (z = start; z <= end; z++){
c.push(z);}
document.write©;
console.log©;
}

var d = range(2,7);
var x = d.length;

var a = 0;
for (let i=0; i<x; i++){
a = a + d[i];
}
console.log(a);
document.write(a);

I also get an error with the 2nd exercise:

Uncaught TypeError: a.indexof is not a function
at reverseArray (arrays3.html:20)
at arrays3.html:24

function reverseArray (){
let a = [0,1,2,3,4,5,6,7,8,9]
for(i=0; i=a.length; i++){
a.indexof(i)= (a.length) - i;
}
return a;
}
reverseArray();

1 Like

1. The sum of a range

<body>

      <input id='argument1' type="text" placeholder="Argument 1">
      <input id='argument2' type="text" placeholder="Argument 2">
      <input id='argument3' type="text" placeholder="Step">

      <button id='ArrayDisplay' name="button">Array</button>
      <button id='SumDisplay2' name="button">Total</button>


      <p id='ArrayP'></p>
      <p id='TotalP'></p>
      <p id='StepTotal'></p>

      <script>

      var ArrayNumber = [];

      //Button Array
      $('#ArrayDisplay').click(function(){
            ArrayNumber = [];
            var x = parseInt($('#argument1').val());
            var y = parseInt($('#argument2').val());
            var z = $('#argument3').val();

            if(x<y){
                if(z==""){
                  while (x<=y){
                    ArrayNumber.push(x);
                    x++;}}
                else{
                    z=parseInt($('#argument3').val());
                      while (x<=y){
                        ArrayNumber.push(x);
                        x=x+z;}}
                }

            else if(x>y){
                if(z==""){
                  while (y<=x){
                    ArrayNumber.push(x);
                    x--;}}
                else{
                    z=parseInt($('#argument3').val());
                      while (y<=x){
                        ArrayNumber.push(x);
                        x=x-z;}}
            }
            $('#ArrayP').text(ArrayNumber);
      });


      //Button Step Total
      $('#SumDisplay2').click(function(){
          var x = parseInt($('#argument1').val());
          var y = parseInt($('#argument2').val());
          var z = $('#argument3').val();
          var total = 0;

          if(x<y){
              if(z==""){
                while (x<=y){
                  total = total + x;
                  x++;}}
              else{
                z=parseInt($('#argument3').val());
                while (x<=y){
                  total = total + x;
                  x=x+z;}}
              }

          else if(x>y){
              if(z==""){
                while (y<=x){
                  total = total + y;
                  y++;}}
              else{
                z=parseInt($('#argument3').val());
                while (y<=x){
                  total = total + y;
                  y=y+z;}}
              }

          $('#StepTotal').text(total);
        });

      </script>
  </body>

2. Reversing an array

<body>

    <h3>Reverse Array</h3>

    <button id='ReverseButton' type="button" name="button">ReverseArray</button>
    <button id='ReverseButton2' type="button" name="button">ReverseArrayInPlace</button>

    <p id='Arraytext'>Initial Array is: </p>
    <p id='Arraytext2'>Reverse Array is: </p>
    <p id='Arraytext3'>Reverse ArrayInPlace is: </p>

    <script>

        var fruitList = ['Mango ', 'Pineapple ', 'Banana '];
        var fruitList2 = ['Mango ', 'Pineapple ', 'Banana '];

        $('#Arraytext').append(fruitList);

        //Reverse Button
        $('#ReverseButton').click(function(){
          $('#Arraytext2').append(fruitList.reverse());
          fruitList=[];
        })

        //ReverseInPlace Button
        $('#ReverseButton2').click(function(){

          var x = 0;
          while(fruitList2[x] != undefined){
              x++;}
          var y = x-1;
          console.log(y);

          var fruitList3 = [];

          while(fruitList2[y] != undefined){
            fruitList3.push(fruitList2[y]);
            y=y-1;}
            console.log(fruitList3);
            $('#Arraytext3').append(fruitList3);
          });

    </script>
  </body>

Hey @Chakingo!

Your code for this first exercise is great! :+1:
Your analysis and comments are also really helpful — both for you and the person reading or working with your code.

You’ve done a really good job with your comments, to be honest, and hopefully my explanation of the reverse step in my post yesterday has helped make things even clearer.

The only couple of things that I would change and/or correct in the comments are:

if (step === 1 && end < start) step = -1;
/* The if function below says that if the end is smaller than start 
   like -10 < -5, the step should be negative too */

It’s confusing that the range goes visually from start to end (and your parameters are also ordered as start (1st) end (2nd)), but then these parameters are inverted in the first if statement. This also makes the comment confusing for the reader. So I would suggest:

if (step === 1 && start > end) step = -1;
/* The if function below says that if the start is greater than the end
   (i.e. a higher number) like -5 > -10, the step should be negative too */
// The sum calculates the range of the array

// CHANGE TO

/* The function sum() calculates the sum total of all the individual
   numbers in the array (i.e. all of the numbers in the range).

But these are only minor points, really, and I’m only mentioning them because you specifically asked for comments, and you seem really keen to make as many improvements as possible, which is great.

Finally, I think you may also be interested in the following alternative way to handle the two possible default step parameters (1 or -1) depending on whether our range is an ascending or descending one. It involves using a ternary operator instead of an if statement, and means you can handle this condition all very concisely within the function header…

function range(start, end, step = start < end ? 1 : -1) {...}

You can find out more about the ternary operator in the MDN web docs:

1 Like

Hi again, @Chakingo!

Reversing an Array (Part 1)
Great :+1:

It doesn’t actually “chop it off” because this function takes the input array and creates a new array which is a mirror image. The original array remains unchanged, which you can test by logging it to the console as well as your new array:

var arrayOne = [1,2,3,4,5];
console.log(reverseArray(arrayOne));   // => [5, 4, 3, 2, 1]
console.log(arrayOne);                 // => [1, 2, 3, 4, 5]

You also have a couple of formatting errors in the code you’ve posted:

  • []  appears as a box
  • the decrement operator (--)  appears as a single dash (–)

I’m not sure if you know, but before you enter your code to post it here in the forum, click on the </> icon in the menu at the top of the text editor. That will give you 2 sets of 3 back ticks…
```
```
If you now add 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 and indentation etc. It’s also easier to spot any copy and paste issues such as the ones I’ve just mentioned above.

For your Reversing an Array you should then end up with something like the following:
(I’ve amended your comment about the while loop for what I mentioned above; and I’ve added the keyword var to your first variable, because it’s always best to declare their scope)

function reverseArray(array) {
   var i = [];
   index = array.length - 1;
/* index starts at full length of the array -1,
   because the zero counts -1 turns into the 5 in the array */
   while(index >= 0) {
      i.push(array[index]);
      index--;
   }
   return i;
/* while loop takes the number at the back and returns it first in order
   in the new array, and then takes the next number in order
   as long as it’s no smaller than zero */
}

I’m going to give you my feedback about Part 2 of this exercise in a separate post :slightly_smiling_face:

1 Like

Hi again, @Chakingo,

Reversing an Array (Part 2 - in place)

This is excellent…you’re on :fire: !
Great code and great analysis — I can see from your comments that you’ve really got into what the code is actually doing :+1:

Hi @Bette,

That’s great that you’re going beyond the course material (that’s only to be encouraged :muscle:) but the exercises for this section were just the first 2 from Chapter 4: Sum of a Range and Reversing an Array (including reversing an array in place). How did you get on with those exercises? It would be nice if you could post your solutions, comments and findings to those here.

I’m going to move this post to a separate topic, and as soon as I get the chance I’ll have a look in a bit more detail at your specific question and get back to you.

Thank you for your patience :slightly_smiling_face:

Hi @Markus_Bielaszka,

Yes, I can see you’re still confused. Let’s see if I can get you started:

In the first part we want to take a predefined array (i.e. a variable outside of our function), feed it into our function, and then output a new array which is a mirror image of the original.

So you want to start with:

function reverseArray(array) {  // originalArray passed in as parameter
// an empty array to be built up within the fx as the new reversed array
   let newArray = [];

   for (...; ...; ...) {
 // THIS IS WHERE THE NEW REVERSED ARRAY IS BUILT UP   
   }
// newArray (reversed version of originalArray) returned to fx call and logged 
   return newArray;        
}

let originalArray = [0, 1, 2, 3, 4, 5];

/* This calls our function with originalArray as the argument,
   then logs the output (our new reversed array) to the console */
   console.log(reverseArray(originalArray)); 

In order to build up the new reversed array you either want to:

  1. Iterate backwards (i--) from the last element of orginalArray (let i = array.length -1;) using the .push() array method to push the value of the last element to the BACK of newArray (the first element pushed to the back will end up in the front after all the other elements have been pushed to the back one by one as well).
    OR
  2. Iterate forwards (i++) from the first element of orginalArray (let i = 0;) using the .unshift() array method to push the value of the first element to the FRONT of newArray (the first element pushed to the front will end up at the end after all the other elements have been pushed to the front one by one as well).

I hope that gives you enough structure and hints to get started, fill in the gaps, and continue on to complete your own solution :slightly_smiling_face:

If you need even more help, then to be honest, you’ll need to look at the model answer and other alternatives posted here in the forum and work back from those to what I’ve given you here.

Good luck! :muscle: :muscle: :smiley:

2 Likes

The sum of a range : For this exercise, I got the first part working just fine, for the second part I peeked at the solutions, and the third part the same. On the first glance it didn’t make much sense to me anything from the third part… But slowly moving it seems just like a puzzle you can upgrade! I would only appreciate if anyone could explain this part to me? https://prnt.sc/svjq6d … I copied btw his code, because I didn’t know how to implement the 3rd assignment, hope that is fine. :slight_smile:

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

  if (step > 0) {
    for (let i = start; i <= end; i += step) newArr.push(i);
  } else {
    for (let i = start; i >= end; i += step) newArr.push(i);
  }
  return newArr;
}
2)
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)));

Reverse array : I got this working by myself first returning as a console.log option, so I just implemented the answer should return in the new array and it was good to go!

var days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];

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

For reverse array in place I did not understand much how to do it, I was thinking of .unshift and .push, so checked couple of videos and I found it way easier to understand this method :

const reverseArrayInPlace = (arr) => {

    let result = []
        for (let element of arr) {

            result.unshift(element)
        }
return result
}

let arr = [1,2,3,4,5]

console.log(reverseArrayInPlace(arr));

If there is something I should know more, or anything to fulfill my knowledge and understanding feel free to let me know! :smiley:

1 Like

Hi @Katoch!

Wow! :star_struck: This is fantastic! You have put so much hard work and effort into this, and I bet you’ve learnt tons in the process. :muscle:

Sorry for taking a while to get back to you. It’s so good that I wanted to take my time reviewing it, as you deserve a thorough one.

I’m going to send you feedback in stages, as I want to get back to you as soon as possible with what I’ve looked at so far:

Sum of a Range

Your functionality and web page presentation for the input parameters, and how you’ve used jQuery and DOM manipulation to handle the button click to call the calculation and display the complete range AND the sum total, is excellent. :star2:

The only functionality asked for in the exercise that it doesn’t handle at the moment is if the step parameter is not given. Can you adapt your code to include a step default parameter which incorporates conditional execution to default to either 1 or -1 depending on whether our range is ascending or descending?

While you’re working on that I’ll review the Reversing an Array part :slightly_smiling_face:

This is an excellent mini-project which brings together many aspects of the course, including jQuery. I hope you continue to build on and develop it as you learn more. For example, what would be great at some stage is if you could include functionality to reset the input fields to empty after clicking on the calculate and display button, so that the user doesn’t have to manually delete their previous input to perform the next calculation.

Maybe you could also add some CSS styling and Generative Art…? :smiley:
(…but, hey! No pressure — what you already produced is excellent!..and I’m getting a bit carried away with the excitement…)

So cool, thanks! I wondered why no one else was addressing it. :face_with_raised_eyebrow:

1 Like

Sum of a Range

//let step = 1;
function range(start, end, step) {
  //console.log(step);
  let chase = [];//this assignment can't be outside function
  if (typeof step === 'undefined') {
    step = 1;
  }
 // console.log(step);
  if (start > end) {
    for (start; start >= end;) {
      chase.push(start);
      start = start + step;
    }
  }
  else {
  for (start; start <= end;) {
  chase.push(start);
    start = start + step;
       }
  }
  return chase;
}

function summ(x) {
    let arrayLength = x.length;
  //console.log("AL = " + arrayLength);
  let result = 0;
  for (let j = 0; j < arrayLength; j++) {
    result += x[j]; 
  }
  return result;
}

Reversing an Array

function reverseArray (aww) {
  newarray = [];
  let size = aww.length;
  for (let i = 0; i < size; i++) {
    newarray[i] = aww.pop();
  }
 return newarray; 
}

function reverseArrayInPlace(ax) {
  //swaps the first and last items, 2nd item with 2nd to last item, ...
  let size = ax.length;
  for (let i = 0; i < Math.floor(size/2); i++) {
    j = ax[i];
    k = ax[size - 1 - i];
    ax[i] = k;
    ax[size - 1 - i] = j;
  }
  return ax;
}

Definitely needed help for reversing the array in place but the solution is logical once you see how to do the swapping.

1 Like

Hi @realsloth,

First of all, please format and organise your code (correct indentation and position of curly brackets etc.) before posting, as then it’s much easier to read, run and check :pray:

Also, please check what you’re posting for obvious copy/paste errors before submitting:

:open_mouth: I assume here you are displaying your range on the web page, and also logging it to the console:

document.write(c);
console.log(c);

If you are doing that instead of returning your output array from your function i.e.

return c;

…then your function call assigned to var d will not evaluate to anything. I think this is why your error is saying that it can’t read d.length because d is undefined.

If this is the only problem, then you should solve it by simply replacing your document.write() and console.log() statements with a return statement, as I’ve shown above.

I can see what you’re trying to do here. Once you’ve got it to work, try turning this part into a function — the sum function it asks for in the exercise.

Forget writing to the document. Both functions should have return statements, so that:

  1. range returns its output range (so it can be printed to the console, and also passed into sum); and
  2. sum returns the sum total of the numbers in the range (so that it can be printed to the console).

You should just have 2 console.log()'s after both functions as follows:

console.log(range(startNumber, endNumber));      // => logs the range as an array
console.log(sum(range(startNumber, endNumber))); // => logs the sum of the array

I’m going to look at what’s happening with your 2nd exercise in a separate post.

Good luck with this one! :slightly_smiling_face:

Hi again, @realsloth,

…always check the spelling, and upper/lower case letters:

.indexOf()   // not .indexof()

I don’t want discourage creativity and innovation, and there are always alternative ways to solve these, but having briefly looked at your code for this exercise, I don’t think you’re going about this the right way. I strongly recommend looking at the hints and starting as it suggests there.

1 Like

Hi @dragos_andrei_87!

Wow! :star_struck: This is fantastic! You have put so much hard work and effort into this, and I bet you’ve learnt tons in the process. :muscle:

It’s so good, that I want to take my time reviewing it, so I’m going to send you feedback for both exercises separately:

Sum of a Range

Your functionality and web page presentation for the input parameters, and how you’ve used jQuery and DOM manipulation to handle the button clicks to call the calculation and display the complete range AND the sum total, is excellent. :star2:

I’ve thoroughly tested it, and it works for most variations. Unfortunately there is one scenario when the calculation of the sum fails in some cases: reverse ranges (i.e. start > end) when the step is greater than 1 — it works for some step values, but fails to calculate the sum of the range correctly for others. The range itself is always output and printed correctly, it’s just a problem with the calculation of the sum.

I’ve noticed that you seem to have over-complicated the function which calculates the sum, and I’m wondering whether simplifying that will solve it. As the exercise in the course book suggests, why don’t you just pass the array of the range from the range function into the sum function and iterate over that, rather than start again from the original input data?

I also think you could improve user-friendliness by making it clear on the web page exactly what the fields Argument 1 and Argument 2 relate to i.e. the start of the range, and the end of the range, respectively.

Otherwise, all the other functionality is excellent, and I particularly like how we don’t need to input negative step numbers i.e. the program automatically converts the step (whatever the interval) into a negative step if the range is a descending one :ok_hand:

While you’re working on updating your program for the points I’ve mentioned above, I’ll review your Reversing an Array part :slightly_smiling_face:

This is an excellent mini-project which brings together many aspects of the course, including jQuery. I hope you continue to build on and develop it as you learn more. For example, what would be great at some stage is if you could include functionality to reset the input fields to empty after clicking on the calculate and display total button, so that the user doesn’t have to manually delete their previous inputs to perform the next calculation.

1 Like

Dear Jonathan,

Thank you for the awesome feedback, support, observations, and recommendation.
Below you can find the code acc. to your suggestions. Hopefully, I understood what you asked. The code acc. to your suggestion for the sum is much simpler than my version. :star_struck: :partying_face: :laughing:

  <body>

      <input id='argument1' type="text" placeholder="Count from...">
      <input id='argument2' type="text" placeholder="Count to...">
      <input id='argument3' type="text" placeholder="Step value">

      <button id='ArrayDisplay' name="button">Array</button>
      <button id='SumDisplay2' name="button">Total</button>


      <p id='ArrayP'></p>
      <p id='TotalP'></p>
      <p id='StepTotal'></p>

      <script>

      var ArrayNumber = [];

      //Button Array
      $('#ArrayDisplay').click(function(){
            ArrayNumber = [];
            var x = parseInt($('#argument1').val());
            var y = parseInt($('#argument2').val());
            var z = $('#argument3').val();

            if(x<y){
                if(z==""){
                  while (x<=y){
                    ArrayNumber.push(x);
                    x++;}}
                else{
                    z=parseInt($('#argument3').val());
                      while (x<=y){
                        ArrayNumber.push(x);
                        x=x+z;}}
                }

            else if(x>y){
                if(z==""){
                  while (y<=x){
                    ArrayNumber.push(x);
                    x--;}}
                else{
                    z=parseInt($('#argument3').val());
                      while (y<=x){
                        ArrayNumber.push(x);
                        x=x-z;}}
                }
            $('#ArrayP').text(ArrayNumber);
      });


      //Button Step Total
      $('#SumDisplay2').click(function(){

          var x = parseInt($('#argument1').val());
          var y = parseInt($('#argument2').val());
          var z = parseInt($('#argument3').val());
          var total = 0;
          function totalSum(){
            ArrayNumber.forEach(myFunction);
            function myFunction(item){
            total+=item;
          }};

          if(x<y){
              if(z==""){
                totalSum();}

              else{
                totalSum();}
              }

          else if(x>y){
              if(z==""){
                totalSum();}

              else{
                totalSum();}
              }

              $('#argument1').val("");
              $('#argument2').val("");
              $('#argument3').val("");

          $('#StepTotal').text(total);
        });

      </script>
  </body>
</html>
1 Like

My exercises:

//a) Range
var arrayNumb=[];
function range (start, end){
  while (start<=end){
    arrayNumb.push(start)
    start++;
  }
}
range (1,10);
arrayNumb
//b) Sum
var counter=0;
function sum(array){
  let i=0;
  while(i < array.length){
    counter=counter+array[i];
    i++;
  }
  return counter;
}
sum(arrayNumb);
//c) Range with index
var arrayNumb=[];
function range (start, end, index){
  if (start<end){
  while (start<=end){
    arrayNumb.push(start);
    start=start+index;
  }
  }
  else {
    while(end<=start){
      arrayNumb.push(start);
      start=start+index;
    }
  }
}
range (5,2,-1);
arrayNumb

// 2. Reversing an array
var abas=[1,2,3,4,5];
var newArray=[];
function reversArray (array){
let i=1;
while(i<=array.length){  
  newArray.push(array[array.length-i]);
  i++;
}
}
reversArray(abas);
newArray
//  reverseArrayInPlace
 var abas=[1,2,3,4,5];
  function reverseArrayInPlace (array){
  for (let i=0; i<Math.floor(array.length / 2); i++){  
    let fig =array[i];
    array[i]=array[array.length-i-1];
    array[array.length-i-1]=fig;
  }
  return array;
  }
  reverseArrayInPlace(abas);
1 Like

Thanks man for taking the time to explain things so thoroughly. I know some people can be very sensitive about critique. I’m not one of them. I feel like I got some answers to my answers and now things have crystallized further

I saw the ternary operator solution in another students post and read up about it on some webpage. I decided to not use that solution in the end since I felt the more basic solution was easier to explain. That being said I will not try not to disregard ternary solutions in future coding

1 Like