Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Array with loop

Tags:

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.

like image 994
Michael Avatar asked Oct 07 '11 12:10

Michael


People also ask

How do you loop through an array in Java?

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.

How do you iterate through an array in Java?

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.

How do you initialize an array and use a for loop?

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.

How to add elements to ArrayList using a 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


2 Answers

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); 
like image 118
aioobe Avatar answered Sep 20 '22 17:09

aioobe


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; 
like image 27
Bala R Avatar answered Sep 18 '22 17:09

Bala R