计算 C 中二维数组中所有元素的和
问题
使用运行时初始化计算二维数组中所有元素的和。
解决方案
在必须存储值表(或)矩阵应用中使用二维数组
语法如下 −
datatype array_ name [rowsize] [column size];
例如,int a[4] [4];
数组中元素数量 = 行大小 * 列大小 = 4*4 = 16
示例
以下是使用运行时初始化计算二维数组中所有元素的和的 C 程序 −
#include<stdio.h>
void main(){
//Declaring array and variables//
int A[4][3],i,j,even=0,odd=0;
//Reading elements into the array//
printf("Enter elements into the array A :
");
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("A[%d][%d] : ",i,j);
scanf("%d",&A[i][j]);
}
}
//Calculating sum of even and odd elements within the array using for loop//
for(i=0;i<4;i++){
for(j=0;j<3;j++){
if((A[i][j])%2==0){
even = even+A[i][j];
}
else{
odd = odd+A[i][j];
}
}
}
printf("Sum of even elements in array A is : %d
",even);
printf("Sum of odd elements in array A is : %d",odd);
}输出
执行上述程序时,将生成以下结果 −
Enter elements into the array A: A[0][0] : 01 A[0][1] : 02 A[0][2] : 03 A[1][0] : 04 A[1][1] : 10 A[1][2] : 20 A[2][0] : 30 A[2][1] : 40 A[2][2] : 22 A[3][0] : 33 A[3][1] : 44 A[3][2] : 55 Sum of even elements in array A is: 172 Sum of odd elements in array A is: 92
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP