Tuesday 15 January 2013

Transpose Of Matrix Using DMA [C Source Code]

This snippet utilizes the dynamic memory allocation function, malloc() and finds the transpose of the user provided matrix.

Below is the source code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
 int **matrix, **transpose, m, n, i, j;
 printf("Enter the size of matrix: ");
 scanf("%d %d", &m, &n);
  
 matrix = malloc(m * sizeof(int));
 transpose = malloc(n * sizeof(int));
 
 for (i = 0; i < m; i++)
 {
  matrix[i] = malloc(n * sizeof(int));
 }
 
 for (i = 0; i < n; i++)
 {
  transpose[i] = malloc(m * sizeof(int));
 }
  
 printf("Enter the matrix:nn");
 for (i = 0; i < m; i++)
 {
  for (j = 0; j < n; j++)
  {
   scanf("%d", &matrix[i][j]);
  }
 }
 
 for (i = 0; i < m; i++)
 {
  for (j = 0; j < n; j++)
  {
   transpose[j][i] = matrix[i][j];
  }
 }
 
 printf("The transpose of given matrix is: nn");
 
 for (i = 0; i < n; i++)
 {
  for (j = 0; j < m; j++)
  {
   printf("%d ", transpose[i][j]);
  }
  printf("n");
 }

 for (i = 0; i < m; i++)
 {
  free(matrix[i]);
 }
for (i = 0; i < n; i++)
 {
  free(transpose[i]);
 }
 free(matrix);
 free(transpose);
 return 0;
}


Below is the sample run:

samar@Techgaun:~$ gcc -Wall -o transpose transpose.c 
samar@Techgaun:~$ ./transpose 
Enter the size of matrix: 2 3
Enter the matrix:

1 2 3
4 5 6
The transpose of given matrix is: 

1 4 
2 5 
3 6