Search code examples
javaarrayssubtraction

How do I subtract two arrays


I have two arrays: A and B. I want to subtract their values, and have the result be stored in array C.

Pseudocode:

Array A[] = (2,2,2)
Array B[] = (1,1,1)

I want to A-B to create Array C:

Array C[] = (1,1,1)

My code:

int []A = new int[3];
for (int i=0; i<3; i++){
    A[i]=IOHelp.readInt("Input numbers as you desire"+i);
}
System.out.println( "The number of  A  array are=("+A[0]+","+A[1]+","+A[2]+")");

// Exact same code for array B.
// Omitted for brevity.

int[] d = new int[3];
for(int i = 0; i <3; i++){
    d[i] = B[i] - A[i];
}
System.out.println("BA=("+d[0]+","+d[1]+","+d[2]+")"); // Prints a new array in this format: BA=(number1, number2, number3)

Now I'm having a few issues setting conditions.


Solution

  • Assuming that arrays A and B are of the same length:

    int[] a = {2, 2, 2};
    int[] b = {1, 1, 1};
    int[] c = new int[a.length];
    
    for(int i = 0; i < a.length; i++){
        c[i] = a[i] - b[i];
    }