c-sharp
  1. c-sharp-program-to-calculate-standard-deviation

Program to Calculate Standard Deviation - (C# Basic Programs)

Calculating standard deviation is a common statistical operation that is used in various applications, including finance and engineering. In this tutorial, we will discuss a program to calculate standard deviation in the C# programming language.

Syntax

The syntax for calculating standard deviation using C# is as follows:

double[] arrayName = { value1, value2, ..., valueN };
double mean = arrayName.Average();
double sumOfSquares = 0;
foreach (double value in arrayName) {
    sumOfSquares += Math.Pow(value - mean, 2);
}
double standardDeviation = Math.Sqrt(sumOfSquares / arrayName.Length);

Example

using System;

namespace StandardDeviation
{
    class Program
    {
        static void Main(string[] args)
        {
            double[] nums = { 10, 20, 30, 40, 50 };
            double mean = nums.Average();
            double sumOfSquares = 0;
            foreach (double num in nums)
            {
                sumOfSquares += Math.Pow(num - mean, 2);
            }
            double standardDeviation = Math.Sqrt(sumOfSquares / nums.Length);
            
            Console.WriteLine("The standard deviation of the given numbers is " + standardDeviation);
        }
    }
}

Output:

The standard deviation of the given numbers is 15.811388300841896

Explanation

The program uses the formula for standard deviation to perform the calculation. First, the average of the input numbers is calculated using the Average() method provided by C#. Then, the sum of squares of the deviations of each number from the mean is calculated using a foreach loop. Finally, the standard deviation is calculated using the formula in the double standardDeviation statement.

Use

Calculating the standard deviation using C# can be useful in many different applications. For example, in finance, it can be used to measure the volatility of a stock, while in engineering, it can be used to measure the variability of a population of measurements. It is an essential tool in statistical analysis and can help in making data-driven decisions.

Summary

In this tutorial, we have discussed a program to calculate the standard deviation using the C# programming language. We have seen the syntax, example, explanation, and uses of standard deviation. By practicing this exercise, programmers can develop a deeper understanding of statistical calculations and become better equipped to handle more complex data analytics projects.

Published on: