Skip to content

Instantly share code, notes, and snippets.

@jamesshah
Last active October 21, 2019 19:06
Show Gist options
  • Save jamesshah/a88aa4c99204f242e9cf8103a4e7070b to your computer and use it in GitHub Desktop.
Save jamesshah/a88aa4c99204f242e9cf8103a4e7070b to your computer and use it in GitHub Desktop.
Implementing Arrays in Java.
//Implementing Matrix Addition
class MatrixMultiplication{
public static void main(String[] args) {
//Creating two matrices
int[][] a = {{1,2,3},{2,3,4}};
int[][] b = {{1,2,3},{2,3,4}};
//Creating empty matrix to store the result
int[][] sum = new int[2][3];
//Printig the elements of the two dimensional array
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
sum[i][j] = a[i][j] + b[i][j];
System.out.print(sum[i][j]+" ");
}
System.out.println(); //To go to new line
}
}
}
//Implementing Two-Dimension Array
class MultidimensionalArray{
public static void main(String[] args) {
//Defining two dimensional array
int[][] array = new int[3][3];
//Inserting elements into two dimensional array
array[0][0] = 1;
array[0][1] = 2;
array[0][2] = 3;
array[1][0] = 4;
array[1][1] = 5;
array[1][2] = 6;
array[2][0] = 7;
array[2][1] = 8;
array[2][2] = 9;
//Printig the elements of the two dimensional array
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
System.out.print(array[i][j]+" ");
}
System.out.println(); //To go to new line
}
}
}
//Implementing Single-Dimension Array
class Arrays{
public static void main(String[] args) {
//Defining an array of 5 elements
int arr[] = new int[5];
//Inserting elements into array
arr[0] = 05;
arr[1] = 10;
arr[2] = 15;
arr[3] = 20;
arr[4] = 25;
//You can also define and insert elements into the element like below
//int arr[] = {5,10,15,20,25}
//Printing all the elements of the array
//length is a pre-defined method of array class in Java which returns the length of an array.
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment