Logo

Programming-Idioms

History of Idiom 195 > diff from v12 to v13

Edit summary for version 13 by m1ritchie:
New Java implementation by user [m1ritchie]

Version 12

2021-08-16, 15:23:19

Version 13

2022-02-10, 23:35: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 main(String args[]){
	int[][] a;
	....*code goes here*....;
	foo(a);
}
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);
    }
Comments bubble
This method assumes an array of size m x n where all arrays n are the same size and that a has at least 1 element.