c-sharp
  1. c-sharp-program-to-calculate-average-using-arrays

Program to Calculate Average Using Arrays - (C# Basic Programs)

Calculating the average of a set of numbers is a common programming exercise that helps improve problem-solving skills. In this tutorial, we will discuss a program to calculate the average of numbers using arrays in C# programming language.

Syntax

The syntax for calculating the average using arrays in C# is as follows:

int[] arrayName = {1, 2, 3, 4, 5};
double sum = 0.0;
double average = 0.0;

for (int i = 0; i < arrayName.Length; i++) {
   sum += arrayName[i];
}

average = sum / arrayName.Length;

Example

using System;

class Program {
    static void Main(string[] args) {
        int[] numbers = new int[5];
        double sum = 0.0;
        double average = 0.0;
        
        Console.WriteLine("Enter 5 numbers:");
        
        for (int i = 0; i < 5; i++) {
            numbers[i] = Convert.ToInt32(Console.ReadLine());
            sum += numbers[i];
        }
        
        average = sum / 5.0;
        Console.WriteLine("The average is {0}", average);
    }
}

Output:

Enter 5 numbers:
1
2
3
4
5
The average is 3

Explanation

The program creates an integer array of size 5 to store the input numbers. It then prompts the user to input 5 numbers, which are stored in the array. The sum of the numbers is computed by iterating through the array and adding each element to the sum variable.

The average is then calculated by dividing the sum by the number of elements in the array (in this case, 5). The result is displayed to the user.

Use

Calculating the average using arrays in C# is a fundamental programming exercise that can help improve problem-solving skills and build proficiency in the language. This program can be useful in a variety of applications, such as statistical analysis, data processing, and more.

Summary

In this tutorial, we discussed a program to calculate the average of numbers using arrays in C# programming language. We covered the syntax, example, explanation, use, and importance of calculating the average using arrays in C#. With this program, programmers can improve their problem-solving skills and build proficiency in C# programming.

Published on: