Summing the numbers in an Array

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

class MinAlgorithm
{
  public static void main ( String[] args ) 
  {
    int[] array =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
    int   min;

    // initialize the current minimum
    min = array[0]; 

    // scan the array
    for ( int val : array )
    { 
       if (   val < min ) 
         min = val ; 
    }
      
    System.out.println("The minimum of this array is: " + min );
  }
}      

Summing the numbers in an Array

Say that you wanted to compute the sum of a list of numbers. You could start with the number on the left, and then proceed left to right through the remaining numbers. Here is a program that implements that algorithm. Its array contains values of type double.

class SumArray
{

  public static void main ( String[] args ) 
  {
    double[] array =  { -47.39, 24.96, -1.02, 3.45, 14.21, 32.6, 19.42 } ;

    // declare and initialize the total
        total =       ;

    // add each element of the array to the total
    for ( int index=0; index < array.length; index++ )
    { 

      total =     ;

    }
      
    System.out.println("The total is: " + total );
  }
}      

QUESTION 18:

Complete the program by filling in the blanks.