How to useNested Loop in Javascript

  • Make an array with five values and initialize it in a variable named nums.
  • Iterate loop from 0 to array length. For finding array length use nums.length where nums is an array.
  • Then, inside the body of the first loop use another loop this loop is iterating from i+1 to nums.length.
  • Then, inside the body of the second array write console.log() for printing the Set of pairs of the numbers.

Example: In this approach, we are going to use a nested loop means loop inside another loop to access pairs.

Javascript




// Print set of pair of numbers
let nums = [1, 2, 3, 4, 5]
 
//Loop for first element
for (let i = 0; i < nums.length; i++) {
 
    //Loop for second element
    for (let j = i + 1; j < nums.length; j++) {
        console.log(`${nums[i]}, ${nums[j]}`);
    }
}


Output

1, 2
1, 3
1, 4
1, 5
2, 3
2, 4
2, 5
3, 4
3, 5
4, 5

Set of pairs of numbers in JavaScript

To Access all sets of pairs of Numbers in an array, We need to access all possible pairs of numbers and need to apply conditions and other operations. In this article, we will see how to access a pair of numbers in JavaScript using different approaches. The first approach is Nested Loop and the second approach is the Recursion Approach.

Table of Content

  • Using Nested Loop
  • Using Recursion

Similar Reads

Approach: Using Nested Loop

Make an array with five values and initialize it in a variable named nums. Iterate loop from 0 to array length. For finding array length use nums.length where nums is an array. Then, inside the body of the first loop use another loop this loop is iterating from i+1 to nums.length. Then, inside the body of the second array write console.log() for printing the Set of pairs of the numbers....

Approach: Using Recursion

...