Java: Array with loop Java: Array with loop arrays arrays

Java: Array with loop


Here's how:

// Create an array with room for 100 integersint[] nums = new int[100];// Fill it with numbers using a for-loopfor (int i = 0; i < nums.length; i++)    nums[i] = i + 1;  // +1 since we want 1-100 and not 0-99// Compute sumint sum = 0;for (int n : nums)    sum += n;// Print the result (5050)System.out.println(sum);


If all you want to do is calculate the sum of 1,2,3... n then you could use :

 int sum = (n * (n + 1)) / 2;


int count = 100;int total = 0;int[] numbers = new int[count];for (int i=0; count>i; i++) {    numbers[i] = i+1;    total += i+1;}// done