Java – sum of elements in the array
I'm doing a simple task for a summer java course. I just hope you can look at my code and see if the way I do it is the best way The goal is to create a simple int array with at least 25 elements, iterate over it and add all the elements I've had some problems, but it looks like I've started working After I solved it, I did some research and saw something similar. People use the for each loop Would this be a better choice? I'm confused about the best way to use against the regular for loop
Anyway, any comment or criticism helps me become a better programmer!
public class Traversals { public static void main(String[] args) { int absenceTotal = 0; // initialize array with 30 days of absences. int absencesArr[] = { 1,3,9,8,23,1,11,5,6,7,10,14,2,4,2 }; for (int i = 0; i < absencesArr.length; i++) { absencesArr[i] += absenceTotal; absenceTotal = absencesArr[i]; } System.out.println("There were " + absenceTotal + " absences that day."); } }
Solution
Do not modify the array I prefer for each loop You should consider that there may be many students, so I may spend a lot of money And format the output Combine them into something similar
long sum = 0; for(int i : absencesArr) { sum += i; } // System.out.println("There were " + sum + " absences that day."); System.out.printf("There were %d absences that day.%n",sum);