📊

Program Guide for Calculating Averages

Mar 17, 2025

Lecture Notes on Writing a Program for Computing Averages

Overview of Program

  • Goal: Compute the average of a list of non-exam scores entered by the user.
  • User Input: The user can enter as many scores as they want.
  • Termination: The user enters a negative number to signal the end of input.

Variables Needed

  • double sum: To keep track of the total sum of scores.
  • int numStudents: To count the number of scores entered.
  • Scanner keyboard: To read user input.
  • double next: To hold the next entered score.

Program Steps

  1. Prompt User: Ask the user to enter scores and a negative number to finish.
  2. Initialize Variables: Set sum, numStudents, and next to zero.
  3. Reading Scores:
    • Use a loop to read scores and add to sum.
    • Increment numStudents for each score.
  4. Loop Condition: Continue while next >= 0.
  5. Compute Average: After loop, divide sum by numStudents.
  6. Output Result: Print the computed average.

Allow Multiple Class Averages

  • Prompt for New Calculation: Ask if user wants to compute another average.
  • Loop for New Class: Use a loop for new class input based on user response (yes/no).
  • Reset Variables: Reinitialize sum and numStudents for each new class.

Nested Loops

  • Use a do-while loop to handle multiple class computations.
  • Boolean Expression: Loop while user answers "yes".

Handling User Input

  • Yes/No Input: Use equalsIgnoreCase to handle different cases for "yes" input.
  • Guard Against Divide by Zero: Check numStudents is not zero before computing average.

Nested Loops Example

  • Printing a matrix of numbers using nested loops.
  • Outer Loop: Controls rows.
  • Inner Loop: Controls columns.
  • Row and Column Variables: Increment appropriately to print matrix.

Break and Continue in Loops

  • Break: Ends the loop immediately.
    • Used in conditional statements to exit loops.
  • Continue: Skips to the next iteration of the loop.
    • Used to skip remaining loop body based on condition.

Debugging Techniques

  • Use Debugger: Utilize built-in debugging tools in IDEs like Eclipse.
  • Temporary Print Statements: Insert print statements to monitor variable values and program flow.

Key Takeaways

  • Avoid using break and continue excessively as it can lead to complex and hard-to-maintain code.
  • Ensure variables are initialized and reinitialized properly within loops.
  • Proper loop design can eliminate the need for redundant code.