How can I sum the product of two two-dimensional arrays?

So I got a code with two arrays: one array contains tickets sold for three cinemas and the other one contains the adult and kid prices. My code outputs the total for every cinema separately (3 lines of output) but I need the total number of those 3. So instead of printing 828 for cinema1, 644 for cinema2, 1220 for cinema3 and I need it to print 2692 (total of 3 cinemas). How can I sum the 3 products with a for loop? Here's the code:

public class Arrays {
    public Arrays() {}
    public static void main(String[] args) {

        float[][] a = new float[][] {{29, 149}, {59, 43}, {147, 11}};
        float[] b = new float[] {8, 4};
        String[] s = new String[] {"cinema 1", "cinema 2", "cinema 3"};
        String[] t = new String[] {"Adults", "Children"};
        int i,j;
        System.out.println("Cinema Complex Revenue\n\n");
        for ( i = 0 ; i <= 2 ; i++ )
        {
            for ( j = 0 ; j < 1 ; j++ )
            {
                System.out.println(s[i] + "\t$" + 
                 (a[i][j] * b[j] + a[i][j + 1] * b[j + 1]));
            }
        }
    }
}

And the output: 1

Upvotes: 0

Views: 146

Answers (2)

hansod1
hansod1

Reputation: 324

All you need is 1 nested for-loop:

Integer totalCost = 0;

for( i = 0 ; i<b.length; i++ ) {
  //you should check if the a[i].length == b.length, and throw an exception if not!
  for( j = 0 ; j<a.length; j++) {
     totalCost += b[i]*a[j][i];
  }
}
System.out.println("Total cost: "+totalCost.toString());

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

Just code what you want.

int i, j;
float sum = 0;
for (i = 0; i < a.length; i++) {
    for (j = 0; j < a[i].length && j < b.length; j++) {
        sum += a[i][j] * b[j];
    }
}
System.out.println(sum);

Or if you want to use only one for loop, it may be

int i;
float sum = 0;
for (i = 0; i < a.length * b.length; i++) {
    sum += a[i / b.length][i % b.length] * b[i % b.length];
}
System.out.println(sum);

Upvotes: 2

Related Questions