Logo

Programming-Idioms

History of Idiom 195 > diff from v13 to v14

Edit summary for version 14 by programming-idioms.org:
[Java] No main method needed

Version 13

2022-02-10, 23:35:05

Version 14

2022-02-11, 14:11:21

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);
    }
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);
    }
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.
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.