二维数组行列互换
[root@localhost CH01]# cat arr_2d_rcexchange.c
#include<stdio.h>
#include<stdlib.h>
#define M 2
#define N 3
int main()
{
int i,j;
int a[M][N] = {1,2,3,4,5,6},b[N][M];
for(i = 0; i < M; i++)
{
for(j = 0;j < N; j++)
{
printf("%d",a[i][j]);
b[j][i] = a[i][j];
}
printf("\n");
}
for(i=0; i<N; i++)
{
for(j=0; j<M; j++)
{
printf("%d",b[i][j]);
}
printf("\n");
}
exit(0);
}
[root@localhost CH01]# make arr_2d_rcexchange
cc arr_2d_rcexchange.c -o arr_2d_rcexchange
[root@localhost CH01]# ./arr_2d_rcexchange
123
456
14
25
36
求最大值及其所在位置
[root@localhost CH01]# cat arr_2d_rcexchange.c
#include<stdio.h>
#include<stdlib.h>
#define M 2
#define N 3
static void change(void)
{
int i,j;
int a[M][N] = {1,2,3,4,5,6},b[N][M];
for(i = 0; i < M; i++)
{
for(j = 0;j < N; j++)
{
printf("%d",a[i][j]);
b[j][i] = a[i][j];
}
printf("\n");
}
for(i=0; i<N; i++)
{
for(j=0; j<M; j++)
{
printf("%d",b[i][j]);
}
printf("\n");
}
return;
}
static void max()
{
int a[M][N] = {2,3,6,555,44,333};
int i,j;
int max = a[0][0],row_index= 0,col_index = 0;
for(i = 0; i < M; i++)
{
for(j = 0; j < N; j++)
{
if(max < a[i][j])
{
max = a[i][j];
row_index = i;
col_index = j;
}
}
}
printf("max:a[%d][%d] = %d\n",row_index,col_index,max);
}
int main()
{
max();
exit(0);
}
[root@localhost CH01]# make arr_2d_rcexchange
cc arr_2d_rcexchange.c -o arr_2d_rcexchange
[root@localhost CH01]# ./arr_2d_rcexchange
max:a[1][0] = 555
求矩阵各行与各列的和
思想:实际预留比原来对一行/一列的空,多出来的一行放每一列的和,多出来的那一列放每一行的和。
[root@localhost CH01]# cat arr_2d_sum.c
#include<stdio.h>
#include<stdlib.h>
static void sum()
{
int a[5][4] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
int i,j;
for(i = 0; i < 4; i++)
{
for(j = 0; j < 3; j++)
{
a[4][3] += a[i][j];
a[4][j] += a[i][j];
a[i][3] += a[i][j];
}
}
for(i = 0; i < 5; i++)
{
for(i = 0; j < 4; j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
return;
}
int main()
{
sum();
exit(0);
}
[root@localhost CH01]# cat sum1.c
#include <stdio.h>
main()
{
int i,j,sumh=0,suml=0;
int arr[3][5]={{1,3,5,7,9},{2,4,6,8,10},{3,5,8,7,6}};
for (i=0;i<3;i++)
{
sumh=0;
for (j=0;j<5;j++)
{
sumh+=arr[i][j];
}
printf("第%d行元素和为%d\n",i+1,sumh);
}
for (i=0;i<5;i++)
{
suml=0;
for (j=0;j<3;j++)
{
suml+=arr[j][i];
}
printf("第%d列元素和为%d\n",i+1,suml);
}
}
求矩阵乘积