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).
I don't want to enter these numbers into the arrays manually, 100 spots would take a while and cost more code.
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.
Java Array – While Loop. Java Array is a collection of elements stored in a sequence. You can iterate over the elements of an array in Java using any of the looping statements. To access elements of an array using while loop, use index and traverse the loop from start to end or end to start by incrementing or decrementing the index respectively.
Java Array is a collection of elements stored in a sequence. You can iterate over the elements of an array in Java using any of the looping statements. To access elements of an array using while loop, use index and traverse the loop from start to end or end to start by incrementing or decrementing the index respectively.
All you have to do is initialize the index that points to last element of the array, decrement it during each iteration, and have a condition that index is greater than or equal to zero. In the following program, we initialize an array, and traverse the elements of array from end to start using for loop.
Then ArrayList.add () is used to add the elements to this ArrayList. Then the ArrayList elements are displayed using a for loop. A code snippet which demonstrates this is as follows
Here's how:
// 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);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With