Exercise>>Find the maximum number in a two-dimensional array, and output the row and column

Parse:

This question only needs to use the ring method to find the maximum value and record the coordinates;

First assume that arr[0][0] is the maximum number of the array, and record the coordinates; the row is 0, and the column is 0;

Compare with each subsequent number, if it is greater than it, replace it, and the coordinates will change accordingly.



Code implementation and code analysis:

include <stdio.h>

#define N 4
#define M 3
int col = 0;
int row = 0;

int fun(int arry[N][M])
{
	int max = 0;
	int i = 0;
	int j = 0;
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < M; j++)
		{
			if (arry[0][0] < arry[i][j])  //假设第一个数最大,用后面的每个数进行比较
			{
				arry[0][0] = arry[i][j];  //如果比他大,就进行替换
				row = i;
				col = j; //记录坐标
			}
		}
	}
	return arry[0][0];   //返回最大的这个数
}

int main()
{
	int a[N][M];
	int i = 0;
	int j = 0;
	int max = 0;
	printf("input a array:");
	for (i = 0; i < N; i++)    //输入这个二维数组
	{
		for (j = 0; j < M; j++)
		{
			scanf("%d",&a[i][j]);
		}
	}
	for (i = 0; i < N; i++)
	{
		for (j = 0; j < M; j++)
		{
			printf("%d  ",a[i][j]);
		}
		printf("\n");
	}
	max = fun(a);    //用max来接收fun函数的返回值
	printf("max=%d row=%d col=%d",max,row,col);   //打印最大值以及最大值所在的行列

	return 0;
}



operation result:

Guess you like

Origin blog.csdn.net/2301_77509762/article/details/130811886