从键盘上输入一个3x3的二维数组,求出主、副两条对角线上的元素之和。 【输入样例】 1 2 3 4 5 6 7 8 9 【输出样例】 s1=15 s2=15c语言
时间: 2023-12-29 08:06:19 浏览: 56
以下是 C 语言程序实现:
```c
#include <stdio.h>
int main() {
int a[3][3], s1 = 0, s2 = 0;
printf("请输入一个3x3的二维数组:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
scanf("%d", &a[i][j]);
if (i == j) {
s1 += a[i][j]; // 计算主对角线元素之和
}
if (i + j == 2) {
s2 += a[i][j]; // 计算副对角线元素之和
}
}
}
printf("s1=%d s2=%d", s1, s2);
return 0;
}
```
程序提示用户输入一个 3x3 的二维数组,然后使用两个循环遍历数组中的元素,并且在计算过程中根据元素的下标来判断该元素是主对角线上的元素还是副对角线上的元素,最后输出两条对角线上的元素之和。
相关问题
求二维数组Ann两条对角线上元素之和使用c语言写出代码
Sure, here is a sample code in C language to find the sum of elements on two diagonals of a 2D array Ann:
```
#include <stdio.h>
int main() {
int Ann[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int sum1 = 0, sum2 = 0;
int i, j;
for(i = 0; i < 3; i++) {
sum1 += Ann[i][i]; // elements on diagonal from top left to bottom right
sum2 += Ann[i][3-i-1]; // elements on diagonal from top right to bottom left
}
printf("Sum of elements on diagonal 1: %d\n", sum1);
printf("Sum of elements on diagonal 2: %d\n", sum2);
return 0;
}
```
This code defines a 2D array Ann with size 3x3 and initializes it with some values. It then uses two nested loops to iterate over all elements in the array and adds elements on the first diagonal (from top left to bottom right) to `sum1` variable and elements on the second diagonal (from top right to bottom left) to `sum2` variable. Finally, it prints out the sums of elements on both diagonals. Hope this helps!
编写程序,从键盘输入一个3行3列的二维数组,交换两条对角线的值,输出交换后的二维数组
好的,这是一个数组交换问题,以下是对角线交换的程序实现:
```
#include <stdio.h>
int main()
{
int array[3][3];
int temp;
// 输入一组3x3的二维数组
printf("请输入一个3行3列的二维数组:\n");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
scanf("%d",&array[i][j]);
}
}
// 交换数组对角线的值
for(int i=0;i<3;i++){
temp = array[i][i];
array[i][i] = array[i][2-i];
array[i][2-i] = temp;
}
// 输出交换后的数组
printf("交换后的二维数组为:\n");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
printf("%d ",array[i][j]);
}
printf("\n");
}
return 0;
}
```
执行结果:
```
请输入一个3行3列的二维数组:
1 2 3
4 5 6
7 8 9
交换后的二维数组为:
3 2 1
4 5 6
9 8 7
```
希望这能帮助到您!