# Multidimensional arrays & Functions

## Lecture 5 - Multidimensional arrays & Functions

### Functions

we can pass to a functions either by:

* reference
* value

Here we pass by **value**

```java
public class Main {
    public static void printMe(int value_of_num) {
        System.out.println(value_of_num);
        value_of_num = 99;
    }


    public static void main(String[] args) {
        int num = 5;
        printMe(num);
        printMe(num);
    }
}
```

```
5
5
```

The function is `void` since it doesn't `return` a value

also here we pass by value

```java
public class Main {
    public static int printMe(int value_of_num) {
        System.out.println(value_of_num);
        value_of_num = 99;
        return value_of_num;
    }


    public static void main(String[] args) {
        int num = 5;
        int x = printMe(num);
        int y = printMe(x);
    }
}
```

```
5
99
```

The function is `int` since we `return` a value

#### Exercise: Palindrome

![Palindrome Program Explained. C-Programs to find a palindrome | by randerson112358 | Medium](https://miro.medium.com/max/986/1*issXrxH-pqC_iXwGMMIEtQ.png)

```java
public class Main {
    public static boolean palindrom(int [] arr){
        for (int i = 0; i < arr.length/2; i++) {
            if (arr[i]!=arr[arr.length-1-i])
                return false;
        }
        return true;
    }


    public static void main(String[] args) {
        int[] arr = {1,2,3,2,1};
        boolean ans = palindrom(arr);
        System.out.println(ans);

        int[] arr2 = {1,3,3,2,1};
        boolean ans2 = palindrom(arr2);
        System.out.println(ans2);
    }
}
```

```
true
false
```

## Multidimensional arrays

![Linear Algebra for Machine Learning | Master Data Science](http://media5.datahacker.rs/2020/03/42-2-1024x542.jpg)

![Scalars, Vectors, Matrices and Tensors with Tensorflow 2.0 - DEV Community](https://res.cloudinary.com/practicaldev/image/fetch/s--oTgfo1EL--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://raw.githubusercontent.com/adhiraiyan/DeepLearningWithTF2.0/master/notebooks/figures/fig0201a.png)

```java
public class Main {
    public static void main(String[] args) {
        int[][] a = {
                {1, 2, 3},
                {4, 5, 6, 9},
                {7},
        };

        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i].length + " ");
        }
        //error out of bounds
        //a[0][3] = 10;
    }
}
```

![](https://cdn.programiz.com/sites/tutorial2program/files/2d-array-variable-length.jpg)

Each array can be a different size

### Exercise: print the matrix and its sum

```java
package com.company;

import java.util.Scanner;

public class Main {
    public static int sumArr2(int [][]arr2) {
        int sum = 0;

        for (int i = 0; i < arr2.length; i++) {
            for (int j = 0; j < arr2[i].length; j++) {
                System.out.print(arr2[i][j] + " ");
                sum += arr2[i][j];
            }
            System.out.println();
        }
        return sum;
    }


    public static void main(String[] args) {
        int n = 2;
        int m = 4;

        int[][] arr = new int[n][m];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = (i*m)+j;
            }
        }

        int sum_of_matrix = sumArr2(arr);
        System.out.println(sum_of_matrix);

    }
}
```

#### Explanation:

here

```java
public class Main {
    public static int sumArr2(int [][]arr2) {
        int sum = 0;
         ...
        return sum;
    }


    public static void main(String[] args) {
        int n = 2, m = 4;
        int[][] arr = new int[n][m];
         ...
        int sum_of_matrix = sumArr2(arr);
    }
}
```

`arr` is passed by

* **reference**
* and not by value&#x20;

### Exercise: Trace of matrix

![Understand The Trace of a Matrix for Beginners - Deep Learning Tutorial](https://www.tutorialexample.com/wp-content/uploads/2019/07/matrix-trace-example.png)

```java
import java.util.Scanner;

public class Main {
    public static int trace(int [][]a2) {
        int sum = 0;

        //check if matrix isn't nxn
        //if matrix is n x m, and n!=m then return -1
        if (a2.length!=a2[0].length)
            return -1;

        for (int i = 0; i < a2.length; i++) {
            for (int j = 0; j < a2[i].length; j++) {
                System.out.print(a2[i][j] + " ");
                if( i == j)
                    sum += a2[i][j];
            }
            System.out.println();
        }
        return sum;
    }


    public static void main(String[] args) {
        int n = 3;
        int m = 3;

        int[][] arr = new int[n][m];

        //create matrix:
        // 0 1 2 
        // 3 4 5 
        // 6 7 8 
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                arr[i][j] = (i*m)+j;
            }
        }
        System.out.println(trace(arr));

    } 
}
```

### Exercise: Transpose

![How to transpose a matrix in Java? Example Tutorial | Java67](https://2.bp.blogspot.com/-8LzbJv0zB3A/WAzRQbxP5eI/AAAAAAAAHYU/MEqPV8JxtLMCSGSQ-0UKZSYlUN3jALZaQCLcB/w1200-h630-p-k-no-nu/Java%2BProgram%2Bto%2BTranspose%2Ba%2BMatrix%2B.png)

```java
public class Main {
    public static int [][] transpose(int [][]a2) {
        int[][] n_arr = new int[a2[0].length][a2.length];


        for (int i = 0; i < a2.length; i++) {
            for (int j = 0; j < a2[i].length; j++) {
                System.out.print(a2[i][j] + " ");
                n_arr[j][i] = a2[i][j];
            }
            System.out.println();
        }
        //completed all
        return n_arr;
    }


    public static void main(String[] args) {
        int n = 3;
        int m = 3;

        int[][] arr = {{1, 0, 5}, {0, 2, 1}, {4, 1, 3}};


        int[][] n_arr = transpose(arr);
    }
}
```

#### Exercise: Check Symmetry of matrix

![Symmetric Matrix & Skew Symmetric Matrix (Definition & Properties)](https://cdn1.byjus.com/wp-content/uploads/2020/07/Symmetric-Matrix-Skew-Symmetric-Matrix.png)

![Introduction to diagonal and symmetric matrices, unit and orthogonal vectors using Python/Numpy examples and drawings](https://hadrienj.github.io/assets/images/2.6/diagonal-and-symmetric-matrices.png)

```java
import java.util.Scanner;

public class Main {
    public static boolean checkSymmetry(int [][]a2) {
        boolean flag = true;

        if (a2.length!=a2[0].length)
            return false;

        for (int i = 0; i < a2.length; i++) {
            for (int j = 0; j < a2[i].length; j++) {
                System.out.print(a2[i][j] + " ");
                if( a2[i][j] != a2[j][i])
                    flag = false;
            }
            System.out.println();
        }
        //completed all
        return flag;
    }


    public static void main(String[] args) {
        int n = 3;
        int m = 3;

        int[][] arr = {{1, 0, 4}, {0, 2, 1}, {4, 1, 3}};

        System.out.println(checkSymmetry(arr));
    }
}
```

### Matrix Multiplication

![A Complete Beginners Guide to Matrix Multiplication for Data Science with Python Numpy | by Chris I. | Towards Data Science](https://miro.medium.com/max/1838/1*YGcMQSr0ge_DGn96WnEkZw.png)

```java
public class Main {
    public static void printMat(int[][] mat){
        for (int i = 0; i < mat.length; i++){
            for (int j = 0; j < mat[i].length; j++)
                System.out.print(mat[i][j] + " ");
            System.out.println();
        }
    }

    public static int[][] matMul(int[][] a, int[][] b) {
        //if error, return this
        if(a[0].length!=b.length){
            System.out.println("error, dims are not compatible");
            return new int[][]{{-1}};
        }

        //start here
        int[][] result = new int[a.length][b[0].length];

        for (int row = 0; row < result.length; row++) {
            for (int col = 0; col < result[row].length; col++) {
                result[row][col] = matMulCell(a, b, row, col);
            }
        }
        return result;
    }

    public static int matMulCell(int[][] a, int[][] b, int row, int col) {
        int cell = 0;
        for (int i = 0; i < b.length; i++)
            cell += a[row][i] * b[i][col];

        return cell;
    }

    public static void main(String[] args) {
        int[][] mat1 = {
                {1, 2, 3},
                {4, 5, 6},
        };

        int[][] mat2 = {
                {10, 11},
                {20, 21},
                {30, 31},
        };

        int[][] res = matMul(mat1, mat2);

        printMat(mat1);
        System.out.println("** times **");
        printMat(mat2);
        System.out.println("== equals ==");
        printMat(res);

    }
}
```

```
1 2 3 
4 5 6 
** times **
10 11 
20 21 
30 31 
== equals ==
140 146 
320 335
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nissan-goldberg.gitbook.io/java101/lesson-5-functions-and-multi-dim-arrays/multidimensional-arrays-and-functions.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
