#include <stdio.h>
void read_array( int row, int col, int a[row][col]);
void fill_arr(int row, int col,int b[row][col], int a[row][col]);
void print_arr(int row, int col, int a[row][col]);
int main(void){
int r1,c1;
printf("Enter number of rows>");
scanf("%d", &r1);
printf("Enter number of columns>");
scanf("%d", &c1);
int arr[r1][c1];
read_array(r1,c1,arr);
int arr2[c1][r1];
fill_arr(c1,r1,arr2,arr);
print_arr(c1,r1,arr2);
}
void read_array( int row, int col, int a[row][col]){
int i,j;
printf("Enter values for %d rows with each row having %d numbers> ", row, col);
for(i=0; i<row; i++){
for(j=0; j<col; j++){
scanf("%d", &a[i][j]);
}
}
}
void fill_arr(int row, int col,int b[row][col], int a[row][col]){
int i,j;
for(i=0; i<row;i++){
for(j=0; j<col; j++){
b[i][j] = a[j][i];
}
}
}
void print_arr(int row, int col, int a[row][col]){
int i,j;
printf("Transpose: \n");
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d ", a[i][j]);
}
printf("\n");
}
}
/*Example for a 3x4 matrix with 1-12 as input:
Expected output:
1 5 9
2 6 10
3 7 11
4 8 12
Actual output:
1 4 7
2 5 8
3 6 9
4 7 10
/*
I'm trying to make a program to make a transpose matrix of a given matrix. Here, the last value of a column is being repeated for some reason. How can I fix this? (I'm aware there are other working codes for transpose matrix on stackoverflow. I need to find the problem in THIS code).
I believe you are mixing up c1
and r1
in the call to fill_array()
.
Also, that function should be called transpose_array()
or copy_transposed()
. fill
suggests you're filling with some fixed value or with zeros.
Hope this is useful.
void fill_arr(int row, int col,int b[col][row], int a[row][col]){
int i,j;
for(i=0; i<row;i++){
for(j=0; j<col; j++){
b[j][i] = a[i][j];
}
}
}
void print_arr(int row, int col, int a[row][col]){
int i,j;
printf("Transpose: \n");
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d ", a[i][j]);
}
printf("\n");
}
}
int main(void){
int r1,c1;
printf("Enter number of rows>");
scanf("%d", &r1);
printf("Enter number of columns>");
scanf("%d", &c1);
int arr[r1][c1];
read_array(r1,c1,arr);
int arr2[c1][r1];
fill_arr(r1,c1,arr2,arr);
print_arr(c1,r1,arr2);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.