ex16 - place the number read in into the next slot in the...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
/* PrintSum * Author: Diana Franklin * Purpose: Read in a list of numbers ending in 0, print out the sum and the numbers in the form: * “15 = 3 + 5 + 9 + 1” */ import java.util.Scanner; public class PrintSum { public static void main(String args[]) { // declare the variables int[] numArray; int sum, count, lastNum, i; Scanner fromScreen; // allocate and initialize variables numArray = new int[100]; // limit to 100 numbers read sum = 0; count = 0; fromScreen = new Scanner( System.in ); // keep reading in numbers until we reach a 0 or have read in 100 numbers do { System.out.print("Enter your next number, 0 if you are done: "); lastNum = fromScreen.nextInt();
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: // place the number read in into the next slot in the array numArray[count] = lastNum; // adjust the sum sum += lastNum; // if the number is not a 0, increment the number of elements read if (lastNum != 0) count++; // only keep looping if we did not read a 0 AND have fewer than 100 nums } while( (lastNum != 0) && (count < 100)); // now we need to print out in the proper format if (count > 0) { System.out.printf("%d = %d ",sum, numArray[0]); for( i = 1; i < count; i++) System.out.printf("+ %d ",numArray[i]); System.out.printf("\n"); } } // end of main method } // end of class...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online