# Chapter 4 - Exercises

My code is not working maybe somebody can assist me please? Ou and happy 2019

``````  <h2>Gib den Start und das Ende ein, um die Summe der iterierten Reichweite zu erhalten</h2>
<input type="start" id="start" />
<input type="end" id="end" />
<button id="OK">OK</button>

<script>

\$("#OK").click(function(){

var start = \$("#start").val();
var end = \$("#end").val();

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

function sum(array){
var x = 0;
for (var i of array){
x+=i;
}
return x;

}

});

</script>

</body>``````

Sum of a Range

``````var myArray = [];
function sumArray(min,max,step){
for (min; step&lt;0 ? min &gt;= max : min &lt;= max; step == null ? min++ : min+=step){
myArray.push(min);
}
console.log(myArray);
y=myArray.length;
var result=0;
for(var i=0; i&lt;y; i++){
result +=  myArray[i];
}
return result;
console.log(result);
``````

}

Range

``````	function range(start, end, step = 1) {
let first = start;
let arr = [];
if (start < end && step > 0) {
for(first; start <= end; start += step) {
arr.push(start);
}
}
else if(start > end && step < 0){
for(start; start >= end; start += step) {
arr.push(start);
}
}

return arr;
}

console.log(range(5, 50, -5));
``````

Sum of elements in array

``````	function sum(arr) {
var a = 0;
for(let i = 0; i < arr.length; i++) {
a +=arr[i]
}
return a;
}
console.log(sum([3,4,5,6,7]));
``````

Reverse array

``````	function reverseArray(arr) {
let arr2 = [];
for(let i = arr.length-1; i >= 0; i-- ) {
arr2.push(arr[i])
}
return arr2;
}
console.log(reverseArray([1, 2, 3, 4, 5, 6, 7, 8, 9]));``````

The Sum of a Range:

``````function range(start, end){
let numset = []
for (let element = start; element < end + 1; element += 1){
numset.push(element)
}
return numset;
}

function sum(numset){
let sumSet = 0;
for (let i = 0; i < numset.length; i += 1){
sumSet = sumSet + numset[i];
}
return sumSet;
}

``````

Modifying the range function to include step size:

``````function range (start, end, step){
let numset = [];
if(step === undefined){
step = 1;
}
for (let element = start; element < end + 1; element += step){
numset.push(element)
}
return numset;
}

``````

Reversing an Array:

1st Method (original Array is preserved):

``````function reverseArray(anArray){
let newArray = [];
for (let i = anArray.length - 1; i != -1; i -= 1){
newArray.push(anArray[i]);
}
return newArray;
}

``````

2nd Method (original Array is changed):

``````function reverseArrayInPlace(anArray){
let j = 0;
for (let i = anArray.length - 1 ; i > (anArray.length - 1)/2; i -= 1){
let placeHold = anArray[j];
anArray[j] = anArray[i];
anArray[i] = placeHold;
j += 1;
}
return anArray;
}
``````

THE SUM OF A RANGE

``````var toReturnArray = [];

function range(a, b){
for(a; a<=b; a++){
toReturnArray.push(a);
}

}

function sum(a, b){
range(a, b);
let total=0;
\$.each(toReturnArray, function(index, value){
total=total+value;
});
}

console.log(sum(1,10));
``````

hello, I need a little help here:
why i canât see user input on this code, what amâi missing?
it pushing it to the list but there is not imput valueâŠ
@ivan

CryptosCity

Submit
``````<!DOCTYPE html>

<html>
<!--NEW CryptosCity WEBSITE-->
<title>CryptosCity</title>

<body>
</ol>

<script>

function redrawlist(){
list.html("");
\$("<li/>").text(value).appendTo(list);
});
}
redrawlist();

redrawlist();

});

</script>

</body>

</html>
``````

THE SUM OF RANGE

``````/*
Write a range function that takes two arguments, start and end, and returns
an array containing all the numbers from start up to (and including) end.
*/

function range(firstNum, lastNum) {

var rangeArray = [];

for (var i = 0; i < 1+lastNum-firstNum; i++) {

rangeArray[i]=firstNum+i;

};

return rangeArray;

};

/*
Next, write a sum function that takes an array of numbers and returns the
sum of these numbers. Run the example program and see whether it does
indeed return 55.
*/

function sum(myArray) {

var mySum = 0;

\$.each(myArray, function(index, value) {
mySum += value;
});

return mySum;

}

/*
As a bonus assignment, modify your range function to take an optional third
argument that indicates the âstepâ value used when building the array. If no
step is given, the elements go up by increments of one, corresponding to the
old behavior. The function call range(1, 10, 2) should return [1, 3, 5, 7,
9]. Make sure it also works with negative step values so that range(5, 2, -1)
produces [5, 4, 3, 2].*/

function rangeBonus(firstNum, lastNum, stepInput) {

var rangeArray = [];
var n = 0;
var stepFor = 1;

if (stepInput) {
stepFor = stepInput;
}
else if (lastNum<firstNum) {
stepFor= -1;
}

if (stepFor>0) {

for (var i = 0; i < 1+lastNum-firstNum; i+=stepFor) {

rangeArray[n]=firstNum+i;
n++;

};

}

else {

for (var i = 0; i > -1+lastNum-firstNum; i+=stepFor) {

rangeArray[n]=firstNum+i;
n++;

};

};

return rangeArray;

};
``````

REVERSING AN ARRAY

``````/* The first, reverseArray, takes an array as argument and produces a new array
that has the same elements in the inverse order.    */

function reverseArray(inputArray) {

var outputArray=[];

for (var i = 0; i < inputArray.length; i++) {

outputArray.push(inputArray[inputArray.length-i-1]);

};

return outputArray;

};

/*  The second, reverseArrayInPlace, does what the reverse method does: it modifies
the array given as argument by reversing its elements. Neither may use the
standard reverse method.*/

function reverseArrayInPlace(inputArray) {

let end = inputArray.length / 2  ;

for (let i = 0; i < end; i++) {

let elem = inputArray[i];
inputArray[i] = inputArray[inputArray.length - 1 - i];
inputArray[inputArray.length - 1 - i] = elem;

};

return inputArray;

};
``````

Under reverseArray, with the code example below, why must we subtract 1 from âarray.length - 1â under the loop. Because without this operation, it gives the index: 0 undefined. Iâm lost here if somebody can please explain. Thanks!

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

The Sum of a Range

``````//creates and returns an array of numbers based on the starting and ending points given
function range(start, end, step){
if (step == undefined){
step = 1;
}

var array = [];
if (end>start){
for (var i=start; i<=end; i+=step) {
array.push(i);
};
}
else{
if (step == 1){
step = -1;
}
for (var i=start; i>=end; i+=step) {
array.push(i);
};
}
return array;
}

//adds all numbers in an array together and returs the sum
function sum(list){
var sum = 0;
var length = list.length;
for (i=0; i<list.length; i++){
sum += list[i];
};
return sum;
}

console.log(range(1, 10, 2));

console.log(sum(range(2,10)));
``````

Reversing an Array

``````var testArray = [1, 2, 3, 4, 5, 6];

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

return(newArray);
}

function reverseArrayInPlace(array){
var length = array.length;
for(var i=array.length-1; i>=0; i--){
testArray.push(array[i]);
};
for (var j = 1; j<=length; j++){
testArray.shift();
};
return(testArray);
}

console.log(reverseArray(testArray));
console.log(reverseArrayInPlace(testArray));
``````

Sum of Range:

array.length gives the quantity of items in an array. For example, an array containing [1, 2, 3, 4, 5] would result in an array.length of 5. Since array objects start at 0 rather than 1, the last item in the array would be equal to array.length-1. So if the example array was named testArray, to access the last element you would use testArray[4].

function range(start, end, increment){
var result [];
if (increment == undefined)
increment = 1;
numLoops = Math.abs(end - start)/increment) +1;
for (var i=0; i<numLoops; i++){
result.push (start);
start += increment;
}
return result;
}

function sum (numArray) {
var arrayTotal = 0;
numLoops = numArray.length;
for (var i=0; i<numLoops; i++) {
arrayTotal += numArray[i];
}
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 x = [{âscoreâ:1}, {âscoreâ:2}, {âscoreâ:3}]

// copy x
y = Object.assign({}, x);
console.log(y);
x.reverse();
console.log(x);
//Result:
// 0: {score :1}
// 1: {score : 2}
// 2: {score :3}

//0: {score:3}
//1: {score:2}
//2: {score:1}

Obviously a beginner, buy that is as good as it gets, for now.

1. Sum of range
``````function range(start, end)
{
let result = [];
result.push(start);
for (let i = 1; i < end - start + 1; i++)
{
result.push(start + i);
}
return result;
}

// Test
console.log(range(1, 10));
console.log(range(2, 5));

function sum(tab)
{
let result = 0;
for (let i = 0; i < tab.length; i++)
{
result += tab[i];
}
return result;
}

// Test
console.log(sum(range(1, 10)));

function rangeBonus(start, end, step = 1)
{
let result = [];
for (let i = 0; i < end - start + 1; i += step)
{
result.push(start + i);
}
return result;
}

// Test
console.log(sum(rangeBonus(1, 10)));
console.log(sum(rangeBonus(1, 10, 2)));
``````
1. Reversing an array
``````function reverseArray(tab)
{
let result = [];
for (let i = 0; i < tab.length; i++)
{
result.push(tab[tab.length - 1 - i]);
}
return result;
}

// Test
chiffres = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
inverseChiffres = reverseArray(chiffres);

function afficheTableau(tab, ordre)
{
let phrase = "Tableau des chiffres dans l'ordre " + ordre + " :";
console.log(phrase);
console.log("-".repeat(phrase.length));

if (ordre.toUpperCase() === "CROISSANT") console.log(tab);
else if (ordre.toUpperCase() === "dĂ©croissant".toUpperCase())   console.log(reverseArray(tab));
else console.log('Error!');
}

afficheTableau(chiffres, "croissant");
console.log("\n\n");

function reverseArrayInPlace(tab)
{
let temp = 0;
for (let i = 0; i < tab.length / 2; i++)
{
temp = tab[i];
tab[i] = tab[tab.length - i - 1];
tab[tab.length - i - 1] = temp
}
return tab;
}

// Test
function afficheTableau(tab, ordre)
{
let phrase = "Tableau des chiffres dans l'ordre " + ordre + " :";
console.log(phrase);
console.log("-".repeat(phrase.length));

if (ordre.toUpperCase() === "CROISSANT") console.log(tab);
else if (ordre.toUpperCase() === "dĂ©croissant".toUpperCase())   console.log(reverseArrayInPlace(tab));
else console.log('Error!');
}

chiffres = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
afficheTableau(chiffres, "croissant");
console.log("\n");

console.log(chiffres === reverseArrayInPlace(chiffres));

// Book's solutions
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;
}
``````

When I read the assignment it felt overwhelming and very challenging, I basically lost steam to push through. I ended up breaking it down into small bite size parts and building up from there. After looking at otherâs answers, I was able to get a better idea but did not make it much easier to understand what the purpose was. The thing I struggled the most with was syntax errors and logic format, were Iâm calling for undefined variables. I had to go back to some real basic lessons because as I was not practicing everyday I lost the skills, this was the most frustrating part of the whole thing, just spending 20min a day on trying to learn a some more code seems to make a huge difference.

``````
/** all functions and variables are loaded before document ready is called, **/
var numberArr =[]; // creates an array from user input

// yourArray() is used to write values of the array to the document
function yourArray(showArray) {
for(x=0; x < showArray.length; x++) {
if(showArray[x] != undefined ){
document.write(" Index No." + x + " Value: " + showArray[x] + "<br>");
}
}
}

// addYourArray is used to calculate the sum of the values in the array
for(x=0; x < showArray.length; x++) {
}
document.write("<br> Sum of Array is:<br> " + ad +"<br><br>");
}

// reverseArray uses a secondary array to store array values is reverse order
function reverseArray() {
var revNumberArr =[];
for(x= numberArr.length; x != 0; x--) {
revNumberArr.push(numberArr[x-1]);
}
return revNumberArr;
}

// reverseArrayInPlace uses a logistical rearrangment of data within the same array to achive a reversed array
function reverseArrayInPlace() {
var l = numberArr.length;
for(x=0; x < l; x++){
numberArr.push(numberArr[x]);
numberArr[x] = numberArr[numberArr.length-1];
}
for(x=l; x<numberArr.length; x++){
delete numberArr[x];
}

yourArray(numberArr);
}

\$("button").click(function(){
var StNum = parseInt(initialNum.value);
var EnNum = finalNum.value;
if (!stepSqnc.value) { // if the step value from the user is null then create input of array will 1 value incruments
if (StNum < EnNum ){ // check to see if the start number is smaller than the end numbers
for(x = StNum; x <= EnNum; x++){
numberArr.push(x);
}
} else {
for(x = StNum; x >= EnNum; x--){
numberArr.push(x);
}
}

} else { // if the user step value is not null then use the step value to create values for the array
if (StNum < EnNum) { // check to see if the start number is smaller than the end numbers
for(x = StNum;x <= EnNum; x = x + parseInt(stepSqnc.value)) {
numberArr.push(x);
}
} else {
for(x = StNum;x >= EnNum; x = x - parseInt(stepSqnc.value)) {
numberArr.push(x);
}
}
}
document.writeln("Your Array: <br>"); // title of the first array that was created by user input
yourArray(numberArr); // prints out the array on screen
reverseArray()
document.writeln("Revered Array: <br>"); // title
yourArray(reverseArray());
document.writeln("<br>Revered Array In Place: <br>");//title
reverseArrayInPlace()
})
});
</script>
<body>
<input id="initialNum" type="text" value="2"></input> <!-- default of 2 used for first number input -->
<input id="finalNum" type="text" value="60"></input> <!-- default of 60 used for last number input -->
<input id="stepSqnc"  type="text" value="4"></input> <!-- default numbers to skip between range -->
<button>submit</button>
</body>
</html>

``````

var Exercise = [âPushupsâ,âSquatsâ, âBurpeesâ, âSitupsâ,âPullupsâ];

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

console.log(Exercise);
console.log(reverseArray(Exercise));
``````

Result in console

(5) [âPushupsâ, âSquatsâ, âBurpeesâ, âSitupsâ, âPullupsâ]
(5) [âPullupsâ, âSitupsâ, âBurpeesâ, âSquatsâ, âPushupsâ]

// 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;
}

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

console.log(range(1, 20))
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);