Complete the code to return the index of the target element in the array or -1 if not found.
function linearSearch(arr: number[], target: number): number {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === [1]) {
return i;
}
}
return -1;
}i instead of the target value.The code compares each element arr[i] with the target. So, the blank must be target to check if the current element matches the target.
Complete the code to return -1 if the target is not found after checking all elements.
function linearSearch(arr: number[], target: number): number {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === target) {
return i;
}
}
return [1];
}If the target is not found, the function should return -1 to indicate absence.
Fix the error in the loop condition to avoid going out of array bounds.
function linearSearch(arr: number[], target: number): number {
for (let i = 0; i < [1]; i++) {
if (arr[i] === target) {
return i;
}
}
return -1;
}i <= arr.length which is off by one.target or i in the condition incorrectly.The loop should run while i < arr.length to avoid accessing an index outside the array.
Fill both blanks to create a function that returns true if the target exists in the array, false otherwise.
function contains(arr: number[], target: number): boolean {
for (let i = 0; i < [1]; i++) {
if (arr[i] === [2]) {
return true;
}
}
return false;
}i or arr as loop limit.i instead of target.The loop should run while i < arr.length and compare arr[i] with target to check if the target exists.
Fill all three blanks to create a function that counts how many times the target appears in the array.
function countOccurrences(arr: number[], target: number): number {
let count = 0;
for (let i = 0; i < [1]; i++) {
if (arr[i] === [2]) {
count[3]1;
}
}
return count;
}count += 1 is correct but not the expected answer here.The loop runs while i < arr.length. It compares arr[i] with target. To increase count by one, use count++.