Abdul Waheed - 2 months ago 10

Java Question

Here is the situation that I have 10 numbers in an Array from 1 to 10 in sequence.

I want to find the sum of those 10 numbers available in array with sequence(1,2,3,....10). Here is the logic I am using I am getting the length of the array and creating a for loop and getting all the members from index of array and adding the sum of all numbers in a variable count as shown in below code

`int [] numArray = new int[10];`

numArray[0] = 1;

numArray[1] = 2;

numArray[2] = 3;

numArray[3] = 4;

numArray[4] = 5;

numArray[5] = 6;

numArray[6] = 7;

numArray[7] = 8;

numArray[8] = 9;

numArray[9] = 10;

int count = 0;

for (int a=0; a< numArray.length; a++) {

count = count + numArray[a];

}

Log.e("test", "The sum of first 10 numbers in sequence is " + count);

Above code is working fine and showing the answer as expected that is count of first 10 numbers is 55. What if I want to find count of first 100 and 1000 numbers? I know I need to iterate loop once again with the length of array.And loop will execute 100 or 1000 times respectively. My question is "Is there any other way of finding the sum of numbers that are in sequence as mentioned above".

I mean without loop.May be there is any formula to find? Any help.

Answer Source

Ok, not sure if I get this correctly, but you simply want to find the sum of numbers from 1 to n? If so that can be as simple as `n*(n+1)/2`

You don't need to create any extra arrays or anything.

For example:

```
int n = 10;
int result = n*(n+1)/2;
```