Logo

Programming-Idioms

History of Idiom 195 > diff from v14 to v15

Edit summary for version 15 by programming-idioms.org:
[Java] Structure for sum

Version 14

2022-02-11, 14:11:21

Version 15

2022-02-11, 14:12:05

Idiom #195 Pass a two-dimensional array

Pass an array a of real numbers to the procedure (resp. function) foo. Output the size of the array, and the sum of all its elements when each element is multiplied with the array indices i and j (assuming they start from one).

Idiom #195 Pass a two-dimensional array

Pass an array a of real numbers to the procedure (resp. function) foo. Output the size of the array, and the sum of all its elements when each element is multiplied with the array indices i and j (assuming they start from one).

Variables
a,foo,i,j
Variables
a,foo,i,j
Code
public static void foo(int[][] a){
       int sum = 0;
       System.out.println("Array a has a size of " + a.length+" by " + a[0].length); 
       for (int i = 0; i<a.length; i++){
           for (int j = 0; j<a[0].length; j++){
               sum = sum + ((i+1)*(j+1)*a[i][j]);
           }
       }
       System.out.println("The sum of all elements multiplied by their indices is: " + sum);
    }
Code
public static void foo(int[][] a){
       System.out.println("Array a has a size of " + a.length+" by " + a[0].length);
       int sum = 0;
       for (int i = 0; i<a.length; i++){
           for (int j = 0; j<a[0].length; j++){
               sum += ((i+1)*(j+1)*a[i][j]);
           }
       }
       System.out.println("The sum of all elements multiplied by their indices is: " + sum);
    }
Comments bubble
This method assumes an array of size m x n where all arrays are the same size and a has at least 1 element.
Comments bubble
This method assumes an array of size m x n where all arrays are the same size and a has at least 1 element.