examples of 2 dimensional arrays in java

  • برمجة جافا

give examples of 2 dimension array in java.

الأجوبة

define 2-dimensional array, with 3 rows and 4 columns:

double[][] scores = new double[3][4];

 

Initializing a two-dimensional array requires enclosing each row’s initialization list in its own set of braces.

int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

Java automatically creates the array and fills its elements with the initialization values.

row 0    {1, 2, 3}

row 1    {4, 5, 6}

row 2    {7, 8, 9}

Declares an array with three rows and three columns.

 

 

 

==================

Creates a 2D array of integers, fills it with increasing integer values, then prints them out.

int[][] table = new int[5][10];  //5 rows and 10 columns

	      // Load the table with values
	      for (int row=0; row < table.length; row++)
	         for (int col=0; col < table[row].length; col++)
	            table[row][col] = row * 10 + col;

	      // Print the table
	      for (int row=0; row < table.length; row++)
	      {
	         for (int col=0; col < table[row].length; col++)
	            System.out.print(table[row][col] + "\t");
	         System.out.println();
	      }

 

Summing The Rows of a Two-Dimensional Array:

int[][] numbers = {{ 1, 2, 3, 4},
                {5, 6, 7, 8},
                {9, 10, 11, 12}};
int total;

for (int row = 0; row < numbers.length; row++)
{
total = 0;
for (int col = 0; col < numbers[row].length; col++)
 total = total+ numbers[row][col];
System.out.println("Total of row " 
                  + row + " is " + total);
}

 

calculate the summation of rows, and average of rows:

		int[][] numbers = { {3,6,12},
				    {1,3,5,7,9},
				    {7,15},
				    {5,4,9,13,12,7,6},
				    {8,9,11,12} };
		int total;
		int[] avg = new int[5];

		for (int i = 0; i < numbers.length; i++)
		{
			total = 0;
			for(int j = 0; j < numbers[i].length; j++)
				total += numbers[i][j]; 
			avg[i] = total / numbers[i].length;
		}
		sort(avg);
		System.out.println();
		for (int i = 0; i < avg.length; i++)
		{
			System.out.print(avg[i] + " ");
		}

//bubble sort:
		public static void sort(int[] array)
		{
			int temp;
				
			for (int i = 0; i < array.length; i++)
			{
				for (int j = i + 1; j < array.length; j++)
				{
					if (array[i] > array[j] )
					{
						temp = array[i];
						array[i] = array[j];	
						array[j] = temp;
					}
				} 	
			}
		}

 

هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...