Dr. A.P.J. Abdul Kalam Technical University, Lucknow
KCS151 / KCS251 Programming for Problem Solving - Using C Language
Lab Exercises
43. Using Dynamic Memory Allocation, Write a program to find the transpose of given matrix.
/*
File: Prgrm43.c
Author: Aditya Saini
Date: Jan 20, 2021
Description: Program to transpose given matrix using dynamic memory allocation.
*/
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int *mat, *t_mat;
int row, col;
int i, j;
//Input no of rows & columns
printf ("Input number of rows: ");
scanf ("%d", &row);
printf ("Input number of columns: ");
scanf ("%d", &col);
//Dynamic memory allocation
mat = (int *) malloc (row * col * sizeof (int));
t_mat = (int *) malloc (row * col * sizeof (int));
//Input matrix
for (i = 0; i <= row - 1; i++)
for (j = 0; j <= col - 1; j++)
{
printf ("Input %d, %d element: ", i + 1, j + 1);
scanf ("%d", (mat + i * col + j));
}
//Calculate transpose matrix
for (i = 0; i <= row - 1; i++)
for (j = 0; j <= col - 1; j++)
*(t_mat + j * row + i) = *(mat + i * col + j);
//Print Matrix
printf ("\nMatrix\n");
for (i = 0; i <= row - 1; i++)
{
for (j = 0; j <= col - 1; j++)
printf ("%d\t", *(mat + i * col + j));
printf ("\n");
}
//Print Transpose Matrix
printf ("\nTranspose Matrix\n");
for (i = 0; i <= col - 1; i++)
{
for (j = 0; j <= row - 1; j++)
printf ("%d\t", *(t_mat + i * row + j));
printf ("\n");
}
};
Output
Input number of rows: 3
Input number of columns: 2
Input 1, 1 element: 1
Input 1, 2 element: 2
Input 2, 1 element: 3
Input 2, 2 element: 4
Input 3, 1 element: 5
Input 3, 2 element: 6
Matrix
1 2
3 4
5 6
Transpose Matrix
1 3 5
2 4 6
No comments:
Post a Comment
Please do not post spam links.