Ive written a program to transpose a matrix of integers using a 2D array, which works fine. The working model is below:
Code:
#include <stdio.h>
#define maxn 10
int main()
{
char proceed = 'Y';
int a[maxn][maxn], n, temp, p, q;
/* p and q used for row and column array subscripts */
printf("Program to transpose n*n integer matrix\n\n");
proceed = 'Y';
while(proceed == 'Y' || proceed == 'y')
{
printf("\nType the order of the matrix (i.e. n) ");
if(scanf("%d", &n)==1 && n>0 && n<=maxn)
{
printf("\nYour matrix is %d by %d\n\n", n,n);
printf("\nType in the matrix row by row\n\n");
for(p=0; p<=n-1; p++)
{
printf("Type in row no %d \n", p+1);
for(q=0; q<=n-1; q++)scanf("%d", &a[p][q]);
}
printf("\nThe matrix you have typed in is\n\n");
for(p=0; p<=n-1; p++)
{
for(q=0; q<=n-1; q++)printf("%d ", a[p][q]);
printf("\n");
}
/* Matrix Transpose */
for(p=1; p<=n-1; p++)
for(q=0; q<p; q++)
{
temp = a[p][q];
a[p][q] = a[q][p];
a[q][p] = temp;
};
printf("\n\nThe transpose is\n\n");
for(p=0; p<=n-1; p++)
{
for(q=0; q<=n-1; q++)printf("%d ", a[p][q]);
printf("\n");
}
}
else printf("\n\nInvalid input\n\n");
printf("Would you like to try to transpose another matrix? (Y or N) ");
proceed=getchar();
while(proceed !='Y' && proceed !='y' && proceed !='n' && proceed !='N')
proceed=getchar();
}
printf("\nThis program is now ending\n\n");
return 0;
}
Now, I want to put the main part of the program, the transpose code, into a function on its own. Ive written the following code but it doesnt work. Any suggestions please?
Code:
#include <stdio.h>
#define maxn 10
int p, q, n;
void transpose(int* a, int N)
{
int temp;
for(p=1; p<=n-1; p++)
for(q=0; q<p; q++)
{
temp = a[p][q];
a[p][q] = a[q][p];
a[q][p] = temp;
};
printf("\n\nThe transpose is\n\n");
for(p=0; p<=n-1; p++)
{
for(q=0; q<=n-1; q++)printf("%d ", a[p][q]);
printf("\n");
}
}
int main()
{
char proceed = 'Y';
int a[maxn][maxn];
printf("Program to transpose n*n integer matrix\n\n");
proceed = 'Y';
while(proceed == 'Y' || proceed == 'y')
{
printf("\nType the order of the matrix (i.e. n) ");
if(scanf("%d", &n)==1 && n>0 && n<=maxn)
{
printf("\nYour matrix is %d by %d\n\n", n,n);
printf("\nType in the matrix row by row\n\n");
for(p=0; p<=n-1; p++)
{
printf("Type in row no %d \n", p+1);
for(q=0; q<=n-1; q++)scanf("%d", &a[p][q]);
}
printf("\nThe matrix you have typed in is\n\n");
for(p=0; p<=n-1; p++)
{
for(q=0; q<=n-1; q++)printf("%d ", a[p][q]);
printf("\n");
}
transpose(a, n);
}
else printf("\n\nInvalid input\n\n");
printf("Would you like to try to transpose another matrix? (Y or N) ");
proceed=getchar();
while(proceed !='Y' && proceed !='y' && proceed !='n' && proceed !='N')
proceed=getchar();
}
printf("\nThis program is now ending\n\n");
return 0;
}