Summing Digits

 

Modules - Structured Programming 2, Data Structures

 

Teacher’s Notes:

========================================================================

This exercise takes a pretty standard accumulation algorithm and makes it a little harder.  Teachers should emphasize that there is theoretically no limit to the number of inputs that a person could enter.

 

Assignment:

========================================================================

 
Write a program that will continuously ask the user to enter numbers from 1 to 100 until they enter a 0.  The program will then output the sum of these numbers.  The program will only add a given number the first time it is entered.  
 
*Optional: The program will ignore non-numeric input.
 

 

Solution (JAVA):

========================================================================

 
import java.util.Scanner;
 
public class Adder {
    public static void main(String[] args)throws Exception {

        boolean[] numbers = new boolean[101];
        /*the default setting for a boolean in JAVA is FALSE
        in other languages, the following block of code may
        be necessary to initialize the array to be false in 
        every index.*/
        for(int x = 0; x < numbers.length; x++)
            numbers[x] = false;
        
        int input = 0, sum = 0;
        Scanner reader = new Scanner(System.in);
        do {
            System.out.print("Enter a number from 1 to 100: ");
            
            //OPTIONAL ERROR TRAP
            /*This is a good idea because it will prevent 
             * an out of bounds exception.
             */
            do
            {
                try {
                    input = reader.nextInt();
                }
                catch(Exception e) {
                    System.out.println("Invalid Input.");
                    String garbage = reader.next();
                }
            }while(input > 100 || input < 0);
            
            /*I like to write the following IF statement
             * like this:
             * if(!numbers[input])
             * but students may find it hard to understand.
             */
            if(numbers[input] == false) {
                numbers[input] = true;
                sum += input;
            }
    
        }while(input != 0);
        
        System.out.println("The sum is: " +sum );
    }
}