Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This assignment will explore arrays (declare, populate, iterate) and functions.

ID: 3605308 • Letter: T

Question

This assignment will explore arrays (declare, populate, iterate) and functions. There are 3 programs pieces.

Refer to the handout Arrays: some methods & properties & many examples

New terminology

Arrays passed as parameters can have their values changed inside a function. A program specification states this decision:

a non-destructive function cannot change any parameter/s value/s

a destructive function can change any parameter/s value/s

Function header is the first line of a function declaration.

1. write one user-defined non-destructive function that displays an array with one index and value pair. No return value.

2. write a user-defined non-destructive function that searches for any occurance of a value and returns its index or -1 if there are no occurances. if there were more than 1 occurance, then it doesn't matter which position is returned.

function header: function arrFind(arr, value)

initiliaze the return value to -1

search the array arr (in a loop) to find the element equal == to value

return the index in the array of value or -1 if it is not in the array

New terminology

Arrays passed as parameters can have their values changed inside a function. A program specification states this decision:

a non-destructive function cannot change any parameter/s value/s

a destructive function can change any parameter/s value/s

Function header is the first line of a function declaration.

Explanation / Answer

1.dumpArray


//function to print arr index and value
function dumpArray(arr) {
  
//loop through the array and print values as specified (i:arr[i])
for (var i = 0; i < arr.length; i++) {
document.write(i + ":" + arr[i] + " ");
}
  
}

//test dump array function
var pets = ["cat", "mouse", "dog", "bird", "hen"];
dumpArray(pets);

2.arrFind


//function to find value in an array
function arrFind(arr, value) {
//loop through array and return index if value matches
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) return i;
}

//retun -1 if value not found
return -1;
}

//test arrFind
var nums = [2, 1, 4, 5, 3, 7];
document.writeln(arrFind(nums, 5));
document.writeln(arrFind(nums, 6));


Output1 :
0:cat 1:mouse 2:dog 3:bird 4:hen

Output2 :
3
-1

**If you have any query , please feel free to comment with details.
**Happy learning :)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote