Nested loop revision :
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
function findPairs(arr) {
for (let i = 0; i <= arr.length; i++) {
for (let j = i + 1; j <= arr.length; j++) {
if (arr[i] + arr[j] === 10)
console.log(arr[i], arr[j])
}
}
}
findPairs(arr)
This function takes an array arr
and finds all pairs of elements in the array that add up to 10. It does this by iterating through each element of the array and comparing it with all subsequent elements using a nested loop. The outer loop iterates n
times, where n
is the length of the array, and the inner loop iterates n-i-1
times, where i
is the current index of the outer loop.
In each iteration of the inner loop, the function checks if the sum of the current element and the element at the inner loop index is equal to 10. If so, the function prints the pair of elements to the console.
What's Inside loop !
The outer loop iterates through each element of the array, one by one, starting with the first element and ending with the last. For each element in the outer loop, the inner loop starts at the next element (i.e., i + 1
) and iterates through all subsequent elements in the array, checking if any of those elements can be paired with the current element to make a sum of 10.
So, for example, when i
is 0 (i.e., the first element of the array), the inner loop starts at 1 (i.e., the second element) and iterates through all subsequent elements in the array (2, 3, 4, 5, 6, 7, 8, 9), checking if any of those elements can be paired with 1 to make a sum of 10.
Then, when i
is 1 (i.e., the second element of the array), the inner loop starts at 2 (i.e., the third element) and iterates through all subsequent elements in the array (3, 4, 5, 6, 7, 8, 9), checking if any of those elements can be paired with 2 to make a sum of 10.
And so on, until the outer loop has iterated through all elements in the array.
I hope this explanation helps clarify what's going on in the loop!
This code can be used to find pairs of numbers in an array that add up to 10. Here are a few examples of real-life problems that this code can help solve:
In a given list of purchase orders, you want to find all pairs of orders that have a total value of $10, so that you can offer a discount to customers who place those orders together.
In a company's database of expenses, you want to identify all pairs of transactions that add up to $10, so that you can investigate whether there are any fraudulent transactions or errors in the accounting.
In a game where players roll two dice and try to get a total of 10, you could use this code to calculate all possible pairs of dice rolls that add up to 10, so that you can help players understand the odds of winning the game.
Overall, this code can be useful in many situations where you need to find pairs of numbers that add up to a specific value, such as 10.
So which orange is bigger ?