循环通过元素的for循环 [英] A for loop that cycle trough elements

查看:99
本文介绍了循环通过元素的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 to 0.
  • Iterate over the 10 items, that is make a FOR loop with an index, say i, ranging from 0 to 9 (or 1 to 10, depending on the programming language).
  • At every iteration update the sum, someting like sum = sum + a[i].


这篇关于循环通过元素的for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆