w3resource

C# Program: Calculate the average of integers in an array

C# Sharp Exception Handling: Exercise-5 with Solution

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:

using System;

class Program {
  static void Main() {
    try {
      // Prompt the user to input the size of the array
      Console.Write("Input the size of the array: ");
      int count = Convert.ToInt32(Console.ReadLine());

      // Create an array of integers based on user-provided count
      int[] numbers = new int[count];

      // Loop to input elements into the array
      for (int i = 0; i < count; i++) {
        Console.Write("Input element-{0}: ", i + 1);
        numbers[i] = Convert.ToInt32(Console.ReadLine());
      }

      // Calculate the average of the array elements
      double average = CalculateAverage(numbers);

      // Display the calculated average
      Console.WriteLine("Average: " + average);
    } catch (EmptyArrayException ex) {
      // Catch block for handling EmptyArrayException
      Console.WriteLine("Error: " + ex.Message);
    } catch (FormatException) {
      // Catch block for handling FormatException when non-integer input is entered
      Console.WriteLine("Error: Invalid input. Please input integers only.");
    } catch (Exception ex) {
      // Catch block for handling other types of exceptions
      Console.WriteLine("An error occurred: " + ex.Message);
    }
  }

  // Method to calculate the average of an array of integers
  static double CalculateAverage(int[] numbers) {
    if (numbers.Length == 0) {
      // Throw EmptyArrayException if the array is empty
      throw new EmptyArrayException("Array is empty. Cannot calculate average.");
    }

    int sum = 0;
    // Loop to calculate the sum of array elements
    for (int i = 0; i < numbers.Length; i++) {
      sum += numbers[i];
    }

    // Calculate and return the average
    return (double) sum / numbers.Length;
  }
}

// Custom exception class for EmptyArrayException
class EmptyArrayException: Exception {
  public EmptyArrayException(string message): base(message) {}
}

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:

Flowchart: C# Sharp Exercises - Calculate the average of integers in an array.

Flowchart: C# Sharp Exercises - Calculate the average of integers in an array.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/csharp-exercises/exception-handling/csharp-exception-handling-exercise-5.php