//Average1.java // Class average program with counter-controlled repetition import java.util.Scanner; public class Average1 { public static void main( String args[] ) { int total, // sum of grades gradeCounter, // number of grades entered grade, // grade value average; // average of all grades // Initialization Phase total = 0; gradeCounter = 1; Scanner input = new Scanner(System.in); // Processing Phase while ( gradeCounter <= 10 ) { // loop 10 times
System.out.println("Enter grade as integer:"); grade = input.nextInt(); total = total + grade; gradeCounter = gradeCounter + 1; } // Termination Phase average = total / 10; // integer division will truncate result System.out.println("Class average is " + average); // display average of exam grades }}
//Average2.java // Class average program with sentinel-controlled repetition
import java.util.Scanner; public class Average2 {
public static void main( String args[] ) { int gradeCounter, // number of grades entered gradeValue, // grade value total; // sum of grades double average; // average of all grades
// Initialization phase
total = 0; gradeCounter = 0;
// Processing phase // prompt for input and read grade from user
Scanner input = new Scanner(System.in); System.out.print("Enter Integer Grade or -1 to Quit"); gradeValue = input.nextInt();
while ( gradeValue != -1 ) {
total = total + gradeValue; gradeCounter = gradeCounter + 1; System.out.print("Enter Integer Grade or -1 to Quit"); gradeValue = input.nextInt(); } // Termination phase if ( gradeCounter != 0 ) { average = (double) total / gradeCounter; System.out.println("Class average is " + average); } else System.out.println("No grades were entered"); } }//Analysis.java // Analysis of examination results. import java.util.Scanner; public class Analysis { public static void main( String args[] ) {
int passes = 0, // number of passes failures = 0, // number of failures student = 1, // student counter result; // one exam result Scanner input = new Scanner(System.in); // user-entered value String output; // output string
// process 10 students; counter-controlled loop while ( student <= 10 ) { System.out.println("Enter result (1=pass,2=fail)" ); result = input.nextInt(); if ( result == 1 ) passes = passes + 1; else failures = failures + 1; student = student + 1; } // termination phase output = "Passed: " + passes + "\nFailed: " + failures; if( passes > 8 ) output = output + "\nRaise Tuition"; System.out.println("Analysis of Examination Results:\n" + output); } }//Increment.java // Preincrementing and postincrementing public class Increment { public static void main( String args[] ) { int c; c = 5; System.out.println( c ); // print 5 System.out.println( c++ ); // print 5 then postincrement System.out.println( c ); // print 6 System.out.println(); // skip a line c = 5; System.out.println( c ); // print 5 System.out.println( ++c ); // preincrement then print 6 System.out.println( c ); // print 6 } }