问. 打印数组所有元素之和的程序。

17 Mar 2025 | 阅读 2 分钟

说明

在这个程序中,我们需要计算数组中所有元素的总和。这可以通过循环遍历数组,并将每次迭代中元素的值添加到变量 sum 来解决。

Program to print the sum of all the elements of an array

数组中所有元素的总和是 1 + 2 + 3 + 4 + 5 = 15。

算法

  1. 声明并初始化一个数组。
  2. 变量 sum 将用于计算元素之和。将其初始化为 0。
  3. 循环遍历数组,并将数组的每个元素添加到变量 sum 中,即 sum = sum + arr[i]。

解决方案

Python

输出

Sum of all the elements of an array: 15

C

输出

Sum of all the elements of an array: 15

JAVA

输出

Sum of all the elements of an array: 15

C#

输出

Sum of all the elements of an array: 15

PHP

输出

Sum of all the elements of an array: 15
 
下一主题#