如何使用 For 循环、While 循环和函数编写 C 程序来查找数组所有元素之和,并附有示例。
此 C 程序 允许用户输入一维数组的大小和行数。接下来,我们使用 For 循环 来迭代元素并执行加法。
#include<stdio.h>
int main()
{
int Size, i, a[10];
int Addition = 0;
// You have specify the array size
printf("\n Please Enter the Size\n");
scanf("%d", &Size);
printf("\nPlease Enter the Elements\n");
//Start at 0, it will save user enter values into array a
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
// Loop Over, and add every item to Addition
for(i = 0; i < Size; i ++)
{
Addition = Addition + a[i];
}
printf("Sum = %d ", Addition);
return 0;
}
使用 for 循环的数组项求和输出
Please Enter the Size
4
Please Enter the Elements
10
20
30
40
Sum = 100
我们已经在 一维数组算术运算 文章中解释了程序流程。因此,我建议您参考 C 编程 以获得更好的理解。
使用 While 循环查找数组所有元素之和的 C 程序
此程序与上面的程序相同,但这次我们使用了 While 循环 来执行 一维数组 的加法。
#include<stdio.h>
int main()
{
int i, Size, a[10];
int j = 0, Addition = 0;
printf("Please Enter the Size of an Array: ");
scanf("%d", &Size);
printf("\nPlease Enter Array Elements\n");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
while(j < Size )
{
Addition = Addition + a[j];
j++;
}
printf("Sum of All Elements in an Array = %d ", Addition);
return 0;
}
Please Enter the Size of an Array: 7
Please Enter Array Elements
10
20
30
40
50
60
90
Sum of All Elements in an Array = 300
使用函数查找数组所有元素之和
这个 示例 与第一个示例相同,但这次我们使用了 函数 来执行加法。
#include<stdio.h>
int SumofNumbers(int a[], int Size);
int main()
{
int i, Size, a[10];
int Addition;
printf("Please Enter the Size of an Array: ");
scanf("%d", &Size);
printf("\nPlease Enter Array Elements\n");
for(i = 0; i < Size; i++)
{
scanf("%d", &a[i]);
}
Addition = SumofNumbers(a, Size);
printf("Sum of All Elements in an Array = %d ", Addition);
return 0;
}
int SumofNumbers(int a[], int Size)
{
int Addition = 0;
int i;
for(i = 0; i < Size; i++)
{
Addition = Addition + a[i];
}
return Addition;
}
