Java Array sum all elements

Introduction

Use a variable named total to store the sum.

Initially total is?0.

Add each element in the array to total using a loop like this:



public class Main {
  public static void main(String[] args) {
    int[] array = new int[5];

    for (int i = 0; i < array.length; i++) { 
      array[i] = (int)(Math.random() * 100); 
    } //from w ww .j a va 2s.c  o m
    
    for (int i = 0; i < array.length; i++) { 
      System.out.print(array[i] + " "); 
    } 

    double total = 0; 
    for (int i = 0; i < array.length; i++) { 
      total += array[i]; 
    } 

    System.out.println(total);
  }
}



PreviousNext

Related