0% found this document useful (0 votes)
5 views3 pages

Java Program to Calculate Average

The document outlines a procedure for calculating the average of two numbers using Java programming. It provides two examples: one with hardcoded values and another that takes user input. Additionally, it includes a task to write a program for calculating the average of three subjects and displaying total and average marks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Java Program to Calculate Average

The document outlines a procedure for calculating the average of two numbers using Java programming. It provides two examples: one with hardcoded values and another that takes user input. Additionally, it includes a task to write a program for calculating the average of three subjects and displaying total and average marks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE – 2

JAVA PROGRAMMING
Procedure to find the average of two numbers,
1) Take two numbers
2) Declare a sum variable
3) Calculate the addition of two numbers and assign them to the sum variable
4) Find average as average = sum/2
5) Finally, display the result of the average value
[Link] a Java program to find the average of two numbers.?
• First, we will develop a simple Java program by hardcoding the values
i.e. required values will be initialized inside the program.
Java program to find average of two numbers
public class Average {
public static void main(String[] args) {

// take two numbers


double num1 = 10;
double num2 = 20;

// declare sum variable


// and initialize with 0
double sum = 0.0;
// declare average variable
double avg = 0.0;

// calculate the sum value


sum = num1 + num2;
// calculate the average value
avg = sum/2;
// display result
[Link]("Average: " + avg );
}
}
Output:-
Average: 15.0

2. Write the Java program to find average of two numbers by


taking input from end-user?
import [Link];
public class Average {
public static void main(String[] args) {

// create Scanner class object


Scanner scan = new Scanner([Link]);

// declare two numbers


double num1 = 0;
double num2 = 0;

// declare sum variable


// and initialize with 0
double sum = 0.0;
// declare average variable
double avg = 0.0;
// take two numbers
[Link]("Enter two numbers: ");
num1 = [Link]();
num2 = [Link]();

// calculate the sum value


sum = num1 + num2;
// calculate the average value
avg = sum/2;

// display result
[Link]("Average: " + avg );
}
}
Output for the different test-cases:-
Enter two numbers: 50 100
Average: 75.0
Enter two numbers: -100 125
Average: 12.5

TASKS TO BE COMPLETED:
1. Write a program in Java to calculate the average of three subjects and
display total and average marks.?

Common questions

Powered by AI

The Java program works by first initializing two variables, num1 and num2, with hardcoded values, for example, 10 and 20. It then declares a sum variable initialized to 0.0 and an average variable. The program calculates the sum of the two numbers (num1 + num2) and assigns it to the sum variable. It then calculates the average by dividing the sum by 2 and stores this value in the avg variable. Finally, it prints the average using System.out.println, resulting in 'Average: 15.0' .

Using the Scanner class for user input provides flexibility and interactivity in comparison to hardcoding values. It allows the program to adapt dynamically to varied inputs from different users instead of being limited to fixed, predefined data. This adaptability is crucial for real-world applications where input variability is a necessity. Moreover, user input allows programs to be more versatile and scalable, as changes to input data do not require code modifications, but merely run-time user interactions .

To modify the program to handle three numbers, you would declare an additional double variable, say num3, and initialize it with either hardcoded values or by reading it from the user using a Scanner object. After obtaining the third number, the calculation for the sum would change to sum = num1 + num2 + num3. The average calculation would also adjust to avg = sum / 3. Finally, use System.out.println() to display both the sum and the average. For example, if num1, num2, and num3 were 10, 20, and 30 respectively, it would display 'Total: 60' and 'Average: 20.0' .

Using data types other than 'double', such as 'float' or 'int', can indeed impact precision. While 'float' uses less memory, it provides lower precision due to a smaller number of decimal places. An 'int' type cannot handle decimal values at all, which would lead to truncation rather than rounding for non-integer averages. Choosing 'double' ensures that calculations maintain a higher degree of precision with decimal values, essential for accurate average representation. Therefore, 'double' is preferred especially when working with high precision requirements .

Hardcoding values can be advantageous in cases where fixed inputs are needed consistently, such as during initial development to simplify debugging and ensure consistent outputs. It can be useful in controlled environments where specific values are predetermined for testing or illustrating a concept to ensure reproducibility. Hardcoding may also be beneficial in scripts where user interaction isn't possible or desired, such as background processes or scheduled tasks that rely on constant data .

Expanding the Java program to include statistics like median and mode increases its complexity significantly. Calculating the median requires sorting the list of numbers, which can be computationally intensive, especially with large datasets. Finding the mode necessitates frequency counting of each number, possibly requiring additional data structures like hashmaps. The potential applications of such expanded functionality are broad, including data analysis, science, finance, and educational tools, providing deeper insights into data distributions beyond simple averages .

The Java program uses the scan.nextDouble() method to read double inputs from users. This method is part of the Scanner class and expects a user to enter a floating-point number. It handles decimal values by directly converting the user input into a double type, thus seamlessly managing numerical inputs that contain decimal points. The value entered by the user is stored in double variables, handling precision automatically .

The program incorporates user input using the Scanner class. It creates a Scanner object to read inputs entered by the user. Two double variables, num1 and num2, are declared and initialized with user-provided values via the scan.nextDouble() method. These values are input when the program prompts the user by displaying 'Enter two numbers:'. After obtaining the numbers, the program calculates the sum and the average in the same manner as the hardcoded version and displays the result using System.out.println .

The programs could be optimized by merging redundant steps. For example, instead of separately declaring the sum variable and then initializing it after user input or hardcoding values, the expression can directly be used during the sum calculation. Additionally, for user-friendly experience and error handling, you could wrap Scanner operations within try-catch blocks to handle non-numeric inputs gracefully. To further enhance the program, encapsulating the logic within a separate method could improve maintainability and reusability of the code. The output could be formatted for better readability, for instance, limiting decimal places .

The program could incorporate exception handling using try-catch blocks around the Scanner input methods. Upon invalid input, such as non-numeric data, an InputMismatchException would be triggered, which can be caught and handled by displaying an error message and prompting the user again for valid input. Additionally, a loop can be used to continue asking for input until valid data is provided. This approach ensures the program does not crash and maintains a smooth user interaction experience .

You might also like