C# Program: Calculate the average of integers in an array
Write a C# program that implements a method that takes an array of integers as input and calculates the average value. Handle the exception if the array is empty.
Sample Solution:
C# Sharp Code:
Sample Output:
Input the size of the array: 5 Input element-1: 1 Input element-2: 2 Input element-3: 3 Input element-4: 4 Input element-5: 5 Average: 3
Input the size of the array: 0 Error: Array is empty. Cannot calculate average.
Explanation:
In the above exercise,
- The Main method prompts the user to input the number of elements in the array using Console.Write() and Console.ReadLine(). The input is converted to an int using Convert.ToInt32() and stored in the count variable.
- An integer array called numbers is created with a size equal to the count.
- A loop prompts the user to enter each array element. The input is converted to an int and stored in the corresponding index of the numbers array.
- The CalculateAverage method is called with the numbers array as an argument. This method calculates the sum of the array elements and divides it by the array length to calculate the average. If the array is empty (length is 0), it throws a custom exception called EmptyArrayException with the message "Array is empty. Cannot calculate average."
- In the Main method, exceptions are handled using catch blocks. If an EmptyArrayException is thrown by the CalculateAverage method, it is caught and an error message is displayed.
- If a FormatException occurs, the user entered a non-integer value. This exception is caught and an appropriate error message is displayed.
- Any other exceptions are caught by the generic catch block, and a general error message is displayed.
Flowchart:
C# Sharp Code Editor:
Improve this sample solution and post your code through Disqus
Previous: File opening with exception handling.
Next: Convert user input string to integer with exception handling.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.