To find if the sum of two numbers in an array equals a specific number k
in JavaScript, you can use nested loops to iterate through the array and check if the sum of two numbers is equal to k
.
Here’s an example:
function findSum(arr, k) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] + arr[j] === k) {
return true;
}
}
}
return false;
}
let arr = [10, 15, 3, 7];
let k = 17;
if (findSum(arr, k)) {
console.log("Sum found");
} else {
console.log("Sum not found");
}
In this example, the findSum
function takes two arguments: an array arr
and a number k
. The function uses nested loops to iterate through the array and check if the sum of two numbers is equal to k
. If a match is found, the function returns true
. If no match is found, the function returns false
. The code then calls the findSum
function with the arr
and k
values and logs the result to the console.
+ There are no comments
Add yours