How to Find the Variance of Numbers in 2D Array in C++?
Last Updated :
23 Jul, 2025
The variance of numbers is a measure of the spread of a set of values which is used to find how much the values in a dataset differ from mean or average. In this article, we will learn how to find the variance of numbers in a 2D array in C++.
Example
Input:
myMatrix = { { 10, 20, 30 },
{ 40, 50, 60 },
{ 70, 80, 90 } };
Output:
Variance: 666.667Variance in a 2D Array in C++
To find the Variance in a 2D array we need to first calculate the mean i.e. the average of all the elements in a given 2D array:
The formula for Mean:
\text{Mean Discrete}\ \mu=E(X)=\sum P_{i}x_{i}
Then use that mean to find the variance (σ2) using the below formula for the set of n values (x₁, x₂,..., xₙ).
Formula for Variance:
\sigma^{2}=\sum P_{i}(x_{i} -\mu)^2
C++ Program to Find the Variance in a 2D Array
The below example demonstrates how we can find a variance in a 2D array in C++.
C++
// C++ Program to find the variance in a 2D array
#include <cmath>
#include <iostream>
using namespace std;
// Function to calculate the overall mean and variance of a
// 2D array
double calculateVariance(int rows, int cols,
int matrix[][3])
{
double sum = 0;
double squaredDiff = 0;
int totalCount = rows * cols;
// Calculate the sum of all elements
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
sum += matrix[i][j];
}
}
// Calculate the overall mean
double overallMean = sum / totalCount;
// Calculate the squared difference from the mean for
// each element
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
squaredDiff
+= pow(matrix[i][j] - overallMean, 2);
}
}
// Calculate variance
double variance = squaredDiff / totalCount;
return variance;
}
int main()
{
const int rows = 3;
const int cols = 3;
int matrix[rows][cols] = { { 10, 20, 30 },
{ 40, 50, 60 },
{ 70, 80, 90 } };
double result = calculateVariance(rows, cols, matrix);
cout << "Variance: " << result << endl;
return 0;
}
Time Complexity: O(N * M), where N is the number of rows and M is the number of columns in the matrix.
Space Complexity: O(1)
Time Complexity: O(N * M)
Auxiliary Space: O(1)
Explore
C++ Basics
Core Concepts
OOP in C++
Standard Template Library(STL)
Practice & Problems