patternjavaModerate
Print the sum of corresponding elements in two arrays
Viewed 0 times
thearrayselementstwoprintsumcorresponding
Problem
In this exercise, I'm supposed to sum up elements from 2 arrays, then display the answer on one line with spaces in between. I did it and my answer got accepted as correct, but I'm wondering if there is a better way to do this since I feel my way was more complicated than it needed to be.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
int n = 11;
int[] firstArray = {811594, 993574, 299729,559604,161945,969851,588210,
692459, 28350,43017,797855};
int[] secondArray = {725888, 233750,191700,944750,380402,319860,766872,764921,
330218,906679, 65309};
List total = new ArrayList<>();
for(int i = 0; i < n; i++){
int sum = firstArray[i] + secondArray[i];
total.add(sum);
}
Integer[] sumArray = total.toArray(new Integer[total.size()]);
for(int i = 0; i < n; i++) {
System.out.print(sumArray[i] + " ");
}
}
}Solution
You don't need to store the intermediate result.
You don't need to give the length of the arrays.
This assumes that the arrays are allways of equal length.
You don't need to give the length of the arrays.
This assumes that the arrays are allways of equal length.
for(int i = 0; i < firstArray.length; i++){
System.out.print((firstArray[i] + secondArray[i]) + " ");
}Code Snippets
for(int i = 0; i < firstArray.length; i++){
System.out.print((firstArray[i] + secondArray[i]) + " ");
}Context
StackExchange Code Review Q#116727, answer score: 11
Revisions (0)
No revisions yet.