Topic: Define a function, use a two-dimensional array as the incoming parameter, enter a 4×4 two-dimensional array in the main function, call the defined function, pass in the matrix, and output the result in the main function. Function function: Make the elements on the two diagonals in the two-dimensional array are 1, and the other elements are all 0.
solution:
#include <stdio.h>
#include <stdlib.h>
int diagonal_assignment(int a[4][4])
{
int i, j;
for (i=0; i<4; i++) {
for (j=0; j<4; j++) {
if (i==j || i+j==3) {
a[i][j] = 1;
}else{
a[i][j] = 0;
}
}
}
return a;
}
void main()
{
int a[4][4],b[4][4];
int i, j;
printf("请向4*4数组逐个输入数据:\n");
for (i=0; i<4; i++) {
for (j=0; j<4; j++) {
scanf("%d", &a[i][j]);
if (j == 3) {
printf("\n");
}
}
}
printf("使二维数组中两条对角线上的元素均为1,其余元素均为 0后的数组:\n");
diagonal_assignment(a);
for (i=0; i<4; i++) {
for (j=0; j<4; j++) {
printf("%d ", a[i][j]);
if (j == 3) {
printf("\n");
}
}
}
system("pause");
}
Note: The incoming actual parameter a in the main function and the formal parameter of the function diagonal_assignment share the same memory unit, and the form of the array passed in the function is its own first address, so the function diagonal_assignment only needs to directly return the address of the modified a , And then call this function in the main function to modify the array a.
Recommended article:
Copyright statement: This article is the original article of the CSDN blogger "This young man surnamed Yu". It follows the CC 4.0 BY-SA copyright agreement. Please attach the original source link and this statement for reprinting.
Original link: https://blog.csdn.net/Laoynice/article/details/79196993