Java:带循环的数组

问题描述:

我需要创建一个包含 100 个数字 (1-100) 的数组,然后计算它们的总和 (1+2+3+4+..+100 = sum).

I need to create an array with 100 numbers (1-100) and then calculate how much it all will be (1+2+3+4+..+100 = sum).

我不想手动将这些数字输入到数组中,100 个点会花费一些时间并且花费更多的代码.

I don't want to enter these numbers into the arrays manually, 100 spots would take a while and cost more code.

我在想一些事情,比如使用 variable++ 直到 100,然后计算所有的总和.不知道具体怎么写.但重要的是它在数组中,所以我也可以稍后说,数组 55 是多少",我可以很容易地看到它.

I'm thinking something like using variable++ till 100 and then calculate the sum of it all. Not sure how exactly it would be written. But it's in important that it's in arrays so I can also say later, "How much is array 55" and I can could easily see it.

方法如下:

// Create an array with room for 100 integers
int[] nums = new int[100];

// Fill it with numbers using a for-loop
for (int i = 0; i < nums.length; i++)
    nums[i] = i + 1;  // +1 since we want 1-100 and not 0-99

// Compute sum
int sum = 0;
for (int n : nums)
    sum += n;

// Print the result (5050)
System.out.println(sum);