I have an integer array for example
int[] abc = {123, 100};
and I want to count its value, like 123 + 100 etc, how can I apply it to my code ?
Am assuming you want to sum up the content of your array. If so then try:
int sum = 0;
for (int i= 0; i < abc.length; i++) {
sum += abc[i];
}
System.out.println(sum);
Just use the advance loop for this:
int sum = 0;
for (int i : abc) {
sum += i;
}
System.out.println(sum);
To calculate the summary of an integer array:
Declare a summary variable with 0 as init value.
Go through each element in the array, then add its value to the summary variable
Solution 1: Using traditional for loop
int[] abc = {123, 100};
int arrayLength = abc.length;
int arraySum = 0;
for (int arrayIndex = 0; arrayIndex < arrayLength; arrayIndex++) {
int value = abc[arrayIndex];
arraySum = arraySum + value;
}
Solution 2: Using enhanced for loop (available from Java 5)
int[] abc = {123, 100};
int arraySum = 0;
for (int value : abc) {
arraySum = arraySum + value;
}
Solution 3: Using Stream API (required Java 8 and API level 24)
int arraySum = Arrays.stream(abc).sum();
In your app, you might need to calculate the summary of an integer array in many places, so you can create a method and use it everywhere you need.
public int calculateSum(int[] array) {
int arraySum = 0;
for (int value : array) {
arraySum = arraySum + value;
}
return arraySum;
}
Use the method
int[] abc = {123, 100};
int arraySum = calculateSum(abc);
int[] abc = {123, 100};
int value=0;
for(int i=0; i<abc.length; i++){
int x =(int) Array.get(abc, i);
value=value+x;
}
System.out.println(value);
Updates
Explanations:
In order to get the total value of the array you need to loop inside the array. So in my case I use for loop, abc.length is method to get the length of the whole array and so helps us to interact with all element inside the array.
I am assigning each element of an array to variable x in each difference loop. Array.get(abc, i) here we are using get method of Array class to get a specific element of array in index i that we assign to x.
Final we had each element of the array to a variable value in every interaction, The last interaction will be our summation of all elements of our array.
Hope this helps,Sorry for my English.
I think there may be better ways to calculate the sum of the elements in a List in Java than this, below shows the source code for a Java “sum the integers in a list”:
int[] abc = {123, 100};
int sum = 0;
for (int value : abc) {
sum = sum + value; // or can be; sum += value;
}
System.out.println(sum);
Note that one thing you have to be careful with in an algorithm like this is that if you’re working with very large numbers, the sum of a list of integers may end up being a long value. I assume you are just adding small number of int (As most “sum” algorithms don’t account for this, but I thought I should mention it.)