C 语言程序,用于打印矩阵边界元素的总和
给定一个矩阵,我们需要打印矩阵的边界元素并显示其总和。
示例
请参考以下给定的矩阵 −
给定矩阵
1 2 3 4 5 6 7 8 9
边界矩阵
1 2 3 4 6 7 8 9
边界元素的总和:1 + 2 + 3 + 4 + 6 + 7 + 8 + 9 = 40
找到边界矩阵总和的逻辑如下−
for(i = 0; i<m; i++){
for(j = 0; j<n; j++){
if (i == 0 || j == 0 || i == n – 1 || j == n – 1){
printf("%d ", mat[i][j]);
sum = sum + mat[i][j];
}
else
printf(" ");
}
printf("
");
}程序
以下是打印矩阵边界元素总和的 C 语言程序 −
#include<stdio.h>
#include<limits.h>
int main(){
int m, n, sum = 0;
printf("
Enter the order of the matrix : ");
scanf("%d %d",&m,&n);
int i, j;
int mat[m][n];
printf("
Input the matrix elements
");
for(i = 0; i<m; i++){
for(j = 0; j<n; j++)
scanf("%d",&mat[i][j]);
}
printf("
Boundary Matrix
");
for(i = 0; i<m; i++){
for(j = 0; j<n; j++){
if (i == 0 || j == 0 || i == n – 1 || j == n – 1){
printf("%d ", mat[i][j]);
sum = sum + mat[i][j];
}
else
printf(" ");
}
printf("
");
}
printf("
Sum of boundary is %d", sum);
}输出
执行上述程序后,将生成以下结果 −
Enter the order of the matrix : 3 3 Input the matrix elements : 1 2 3 4 5 6 7 8 9 Boundary Matrix : 1 2 3 4 6 7 8 9 Sum of boundary is 40
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP