Find Average

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 50:-  Find Average

To find the average (also known as the arithmetic mean) of a set of numbers in Java, you need to sum up all the numbers and then divide the sum by the total count of numbers. Here's a Java method to calculate the average of an array of integers:

javaCopy code
public class AverageCalculator { public static double findAverage(int[] arr) { int sum = 0; for (int num : arr) { sum += num; } return (double) sum / arr.length; } public static void main(String[] args) { int[] numbers = {5, 10, 15, 20, 25}; double average = findAverage(numbers); System.out.println("Average: " + average); // Output: 15.0 } }

In this example, we have a method findAverage that takes an integer array arr as an argument. Inside the method, we declare a variable sum to store the sum of all elements. We use a for-each loop to iterate through the array and add each element to the sum variable.

After calculating the sum, we divide it by the length of the array (arr.length) to get the average. Note that we cast the sum to double before dividing to ensure that the division is done in floating-point arithmetic, giving us a more precise result.

In the main method, we demonstrate how to use the findAverage method with a sample array of numbers. The output will be the average of the numbers, which is 15.0 in this case.

Keep in mind that if the array is empty, you should handle that case separately to avoid division by zero. In the above example, we assume that the array has at least one element to calculate the average.


Disclaimer:-

Under Section 107 of the copyright act 1976, allowance is made for fair use for purposes such as criticism, comment, news reporting, scholarship, and research. Fair use is a use permitted by copyright statute that might otherwise be infringing. Non-profit, educational, or personal use tips the balance in favor of fair use.

 

8. Array

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?