Description
* In two dimensional array first subscript denotes row, second denotes column. * Two dimensional array is an array of one dimensional arrays. * In 2D array, size of first dimension can be omitted. example: int price[][3] = {{45,26,34},{48,65,97}}; * To initialize the entire 2D array to zeros, specify the first value as zero. example: int price[1][2]={0}; * 2D array is stored in contiguous memory location.
C/C++
/* C program to Read and Display 2D Array */ //Save it as ReadDisplay2DArray.c #include<stdio.h> int main(){ int i, j, m, n; printf("Enter the number of rows of array : "); scanf("%d",&m); printf("Enter the number of columns of array : "); scanf("%d",&n); //Declaring 2D array int arr[m][n]; //Reading input for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf("arr[%d][%d] : ",i,j); scanf("%d",&arr[i][j]); } } //Displaying Output printf("The entered array : \n"); for(i=0;i<m;i++) { for(j=0;j<n;j++) { printf("%d ",arr[i][j]); } printf("\n"); } }
Input: Enter the number of rows of array : 3 Enter the number of columns of array : 3 arr[0][0] : 9 arr[0][1] : 8 arr[0][2] : 7 arr[1][0] : 6 arr[1][1] : 5 arr[1][2] : 4 arr[2][0] : 3 arr[2][1] : 2 arr[2][2] : 1 Output: The entered array : 9 8 7 6 5 4 3 2 1
Java
/* Java program to Read and Display 2D Array */ //Save it as ReadDisplay2DArray.java import java.io.*; import java.util.Scanner; public class ReadDisplay2DArray { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int i, j, m, n; System.out.println("Enter the number of rows of array : "); m = scanner.nextInt(); System.out.println("Enter the number of columns of array : "); n = scanner.nextInt(); //Declaring 2D array int arr[][] = new int[m][n]; //Reading input for(i=0;i<m;i++) { for(j=0;j<n;j++) { System.out.println("arr["+i+"]"+"["+j+"] : "); arr[i][j] = scanner.nextInt(); } } //Displaying Output System.out.println("The entered array : "); for(i=0;i<m;i++) { for(j=0;j<n;j++) { System.out.print(arr[i][j]+ " "); } System.out.println(); } } }
Input: Enter the number of rows of array : 3 Enter the number of columns of array : 3 arr[0][0] : 9 arr[0][1] : 8 arr[0][2] : 7 arr[1][0] : 6 arr[1][1] : 5 arr[1][2] : 4 arr[2][0] : 3 arr[2][1] : 2 arr[2][2] : 1 Output: The entered array : 9 8 7 6 5 4 3 2 1
Related Programs
1) Program to Transpose a matrix2) Program to Add two Matrices
3) Program to Multiply two Matrices
4) Program to Find the smallest missing number
5) Program to Search for an Element in an Array
6) Program to Rearrange an array such that arr[i]=i
7) Program to Find missing odd number in first n odd number
8) Program to find maximum and second maximum if elements of array is space separated input
9) Program to Print How Many Numbers Smaller than Current Number
10) Remove Duplicate Elements From Array