Program in C to transpose a 2D array
Transpose means changing the rows of 2D array into columns and columns into rows. Below is the code in the C programming language to transpose a two dimensional array -
/* C program to transpose the 2D array */
#include<stdio.h>
void main()
{
int a[10][10], b[10][10], m, n, i, j;
printf("\nEnter number of rows & columns of aray : ");
scanf("%d %d", &m, &n);
printf("\nEnter elements of 2-D array:\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d", &a[i][j]);
}
}
printf("\n\n2-D array before transposing:\n\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
printf("\t%d", a[i][j]);
}
printf("\n\n");
}
/* Transposing array */
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
b[j][i] = a[i][j];
}
}
printf("\n\n2-D array after transposing:\n\n");
for(i=0; i<n; i++)
{
for(j=0; j<m; j++)
{
printf("\t%d", b[i][j]);
}
printf("\n\n");
}
getch();
}
We create the 2D array first and after that it’s transpose is done which is stored in new 2D array. Hence the result is printed.
Input-
Enter number of rows & columns of aray : 3 x 3
Enter elements of 2-D array:
25 12 4 62 34 23 6 4 3
Output-
2-D array before transposing:
25 12 4
62 34 23
6 4 3
2-D array after transposing:
25 62 6
12 34 4
4 23 3
No comments yet