Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Exercise 2D Arrays

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

 

initialize and declare a multidimensional array.

import java.io.*;

public class 2Darray {


public static void main(String[] args)
{

int[][] arr = new int[10][20];


arr[0][0] = 1;

System.out.println("arr[0][0] = " + arr[0][0]);


}
}

Printing 2D arrays

public class TwoDdirectmethod {


public static void main(String[] args)
{

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

System.out.println("Elements of the array are: ");


for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++)
//prints the array elements
System.out.print(arr[i][j] + " ");
//throws the cursor to the next line
System.out.println();
}

}
}

Assessing the elements of array

import java.io.*;
public class {
public static void main(String[] args)
{

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

for (int i = 0; i < 2; i++)


for (int j = 0; j < 2; j++)
System.out.println("arr[" + i + "][" + j + "] = "+ arr[i][j]);
}
}
Initializing arrays with input values

import java.util.Scanner;
/**
*
* @author user
*/
public class ArrayInputExample2 {
public static void main(String args[])
{
int m, n, i, j;

Scanner sc=new Scanner(System.in);


System.out.print("Enter the number of rows: ");
//taking row as input
m = sc.nextInt();

System.out.print("Enter the number of columns: ");


//taking column as input
n = sc.nextInt();

// Declaring the two-dimensional matrix


int array[][] = new int[m][n];
// Read the matrix values
System.out.println("Enter the elements of the array: ");

//loop for row


for (i = 0; i < m; i++)
//inner for loop for column
for (j = 0; j < n; j++)
array[i][j] = sc.nextInt();
//accessing array elements
System.out.println("Elements of the array are: ");
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++)
//prints the array elements
System.out.print(array[i][j] + " ");
//throws the cursor to the next line
System.out.println();
}
}
}
Passing 2D arrays to method

import java.util.Scanner;
public class PassTwoDimensionalArray {
public static void main(String[] args) {
int[][] m = getArray(); // Get an array

// Display sum of elements


System.out.println("\nSum of all elements is " + sum(m));
}

public static int[][] getArray() {


// Create a Scanner
Scanner input = new Scanner(System.in);

// Enter array values


int[][] m = new int[3][4];
System.out.println("Enter " + m.length + " rows and "
+ m[0].length + " columns: ");
for (int i = 0; i < m.length; i++)
for (int j = 0; j < m[i].length; j++)
m[i][j] = input.nextInt();

return m;
}

public static int sum(int[][] m) {


int total = 0;
for (int row = 0; row < m.length; row++) {
for (int column = 0; column < m[row].length; column++) {
total += m[row][column];
}
}

return total;
}
}

You might also like