When multiple variables of similar type are given one variable name with two subscripts which can be represented in matrix form i.e. number of rows and columns, such a variable is called two dimensional array.
Declaration of 2-D array:
Declaration of 2-D array:
An array must be declared before they are used, so that space for them is allocated before use.
data_type variable_name[number of rows][number of columns];
Example:-
int x[2][3];
int x[3][2];
This will reserve space for 6 elements of array as,
float amount[4][2];
char name[7][10];
Wrong declarations:-
int x[][]; //wrong
int x[2][]; //wrong
int x[][3]; //wrong
float amount[-2][9]; //wrong
int n=7;
char name[n][n]; //wrong
Initialization of 2-D array:
When an array is declared,its elements will be containing unknown values. We can give them values when they are declared, this is called initialization of array's elements.
data_type variable_name={list of values separated by comma};
Example:-
int x[2][3]={10,20,30,40,50};
This will initialize array with these values,
Another methods for initialization:-
int x[2][3]={ {10,20} , {30,40,50} };
This will initialize array with these values,rest values will be zeroes
int x[][3]={10,20,30,40,50};
int x[2][]={10,20,30,40,50};
This will produce compilation error as number of columns are not confirmed.
int x[][]={10,20,30,40,50};
This will produce compilation error as number of columns are not confirmed.
Accessing 2D array's elements:
To access elements of a two dimensional array, we use array's name with two subscripts. The value inside first subscript indicates row number and inside second subscript indicates column number.
x[0][1] indicates second element i.e. first row and second column entry.
x[1][2] indicates second row and third column entry of the array
Code 1:
#include<stdio.h> void main() { int x[5][5]; int i,j,r,c; printf("\nenter number of rows and columns"); scanf("%d %d",&r,&c); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("\nEnter x[ %d ][ %d ]==> ",i,j); scanf("%d",&x[i][j]); } } printf("\nMatrix is::\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf(" %d ",x[i][j]); } printf("\n"); } }
Output:
Code 2:
Transpose of a matrix:-
Transpose matrix of a matrix is a new matrix that shows columns entries and rows entries of original matrix as rows entries and columns entries in it.
#include<stdio.h> void main() { int x[5][5]; int i,j,r,c; printf("\nenter number of rows and columns"); scanf("%d %d",&r,&c); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf("\nEnter x[ %d ][ %d ]==> ",i,j); scanf("%d",&x[i][j]); } } printf("\nMatrix is::\n"); for(i=0;i<r;i++) { for(j=0;j<c;j++) { printf(" %d ",x[i][j]); } printf("\n"); } printf("\nTranspose Matrix is::\n"); for(i=0;i<c;i++) { for(j=0;j<r;j++) { printf(" %d ",x[j][i]); } printf("\n"); } }
Output:





No comments:
Post a Comment