Search code examples
javaarraysmultiplication

How can I multiplicate two arrays in a way that the first value of arrayA multiply the last value of arrayB?


How can I multiplicate two arrays in a way that the first value of arrayA multiply the last value of arrayB?

public static void main(String[] args) throws IOException {
    int numbersA[] = new int[5];
    int numbersB[] = new int[5];
    int numbersC[] = new int[5];

    for (int i = 0; i < numbersA.length; i++) {
        System.out.print("Please insert a number for the first array: ");
        numbersA[i] = Integer.parseInt(in.readLine());
    }
    System.out.println(Arrays.toString(numbersA));

    for (int i = 0; i < numbersB.length; i++) {
        System.out.print("Please insert a number for the second array: ");
        numbersB[i] = Integer.parseInt(in.readLine());
    }
    System.out.println(Arrays.toString(numbersB));

    System.out.print("The multiplication of the two arrays (the first one with the last one and consecutively) are: ");
    for (int i = 0; i < numbersC.length; i++) {
        numbersC[i] = numbersA[i] * numbersB[(numbersB.length) - 1 - i];
    }
    System.out.println(Arrays.toString(numbersC));
}

}


Solution

  • Your first element(i.e. index 0) of numbersA[ ] should be multiplied by last element(i.e. index 9) of numbersB[ ] array. Similarly second element(i.e. index 1) of numbersA[ ] should be multiplied by second last element(i.e. index 8) of numbersB[ ]. Like shown below:

    public static void main(String... ars) {
    
        System.out.println("enter the length of arrays");
        Scanner sc = new Scanner(System.in);
    
        int len = sc.nextInt();
    
    
        int numbersA[] = new int[len];
        int numbersB[] = new int[len];
        int numbersC[] = new int[len];
    
        Random rand = new Random();
    
        System.out.println("enter the values of first array");
        for (int i = 0; i < numbersA.length; i++) {
            numbersA[i] = sc.nextInt();
        }
        System.out.println(Arrays.toString(numbersA));
    
        System.out.println("enter the values of second array");
        for (int i = 0; i < numbersB.length; i++) {
            numbersB[i] = sc.nextInt();
        }
    
        System.out.println(Arrays.toString(numbersB));
    
    
        out.println("The multiplication of the two arrays (the first one with the last one and consecutively) are: ");
        for (int i = 0; i < numbersC.length; i++) {
            numbersC[i] = numbersA[i] * numbersB[(numbersB.length)-1-i];
        }
    
        System.out.println(Arrays.toString(numbersC));
    }