Java program to find index of two numbers from array their sum is equal to target(input) number

Write a java program to find the index of two numbers from an array their sum should be equal to the input number or the target number.

For example, an array contains {2, 4, 7, 2, 8} and the target number is 12. Then the output number will be 4, 8 that is available on the array index 1, 4

Input :

nums = {2,4,7,2,8}

target = 10

Output :

0  4

In the above input and output sample, we will see that give input in an array and set a target to like here we set 10 then, in array add two elements whose sum is 10 and then print those elements index value in the output.

Algorithm to Find index of two numbers from array their sum is equal to input number

  1. Take an array as input and assign elements in the array.
  2.  Set a target.
  3. Create nested loop in first loop set i =0; i<nums.length and increamnet of i.
  4. In second loop set j =i; j<nums.length and increament of j .
  5. In second loop create if condition and give condition  nums [j] == target – nums[i].
  6. And return a new array whose elements are i and j.
  7. Set all these attributes in the results array and print the results array as an output.
  8. Print the index value of the sum of two numbers with the target.

Java code to find an index of two numbers from array their sum is equal to target(input) number

public class Twosum {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int [] numbers = new int [] {2,4,7,2,8};
        int target = 12;
        int [] result = twoSum(numbers, target);
        System.out.print(result [0]+ " " + result[1]);

    }

    public static int[] twoSum(int[] nums, int target) {
        for(int i =0;i<nums.length; i++){
            for(int j =i;j<nums.length;j++){
                if (nums[j]==target - nums[i]){
                    return new int []{i,j};
                }
            }
        }
        return null;
    }
}

Output of program

Code Explanation:

Step 1: Start.

Step 2: Create a class and main method.

Step 3: Declare one array and assign an element in the array, and also declare one target and set target.

Step 4: Create a method twoSum and pass two parameter numbers, target.

Step 5: Then, create a nested loop in a method in the first loop that gives condition i<nums.length and in the second loop give a condition for j j<nums.length.

Step 6 : In second loop create if condition and its condition is (nums[j]==target – nums[I]).

step 7:  Return the new array and i , j.

Step 8: Create a new Array in the main method and assign method and parameters to result from array.

Step 9: Print the result array and print a suitable message.