循环通过元素的for循环 [英] A for loop that cycle trough elements
本文介绍了循环通过元素的for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,请帮我解决java中的以下数组
一个FOR循环,循环遍历每个元素并将它们一起添加..显示一个将通知用户的句子算法结束时数组中元素的总值...
序列:2,8,18,32,50,72,98,128,168,200
解决方案
尝试:int [] data = new int [] { 2 , 8 , 18 , 32 , 50 , 72 , 98 , 128 , 168 , 200 };
int total = 0 ;
for ( int index = 0 ; index < data.Length; index ++)
{
total + = data [index];
}
Console.WriteLine(总计);
但更好的方法:
int [] data = new int [] { 2 , 8 , 18 , 32 , 50 , 72 , 98 , 128 , 168 , 200 跨度>};
Console.WriteLine(data.Sum(x = > x));
< blockquote>你需要查看你最喜欢的语言的文档,以便实际编码。
一个简单的方法是:
- 初始化
总和
到0
。 - 迭代
10
项目,即使用索引进行FOR
循环,例如i
,范围从0
至9
(或1
至10
,具体取决于编程语言。 - 在每次迭代时更新总和,有点像
sum = sum + a [i]
Hello can you please help me with the following array in java
A FOR loop that will cycle through each of these elements and add them together ..displaying a sentence that will notify the user of the total value of the elements in the array with the end of the algorithm...
sequence: 2,8,18,32,50,72,98,128,168,200
解决方案
Try:int[] data = new int[] {2,8,18,32,50,72,98,128,168,200}; int total = 0; for (int index = 0; index < data.Length; index++) { total += data[index]; } Console.WriteLine(total);
But a better way:
int[] data = new int[] {2,8,18,32,50,72,98,128,168,200}; Console.WriteLine(data.Sum(x => x));
You need to check out the documentation of your favourite language, in order to actually coding it.
A simple approach would be:
- Initialize the
sum
to0
.- Iterate over the
10
items, that is make aFOR
loop with an index, sayi
, ranging from0
to9
(or1
to10
, depending on the programming language).- At every iteration update the sum, someting like
sum = sum + a[i]
.
这篇关于循环通过元素的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文