How To Find The Variance Of Numbers In 2D Array In C++ - C++ Programming Tutorial
C++ Course / Arrays / How To Find The Variance Of Numbers In 2D Array In C++

How To Find The Variance Of Numbers In 2D Array In C++

BLUF: Mastering How To Find The Variance Of Numbers In 2D Array In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: How To Find The Variance Of Numbers In 2D Array In C++

C++ is renowned for its efficiency. Learn how How To Find The Variance Of Numbers In 2D Array In C++ enables low-level control and high-performance computing in the tutorial below.

In this guide, we will explore the process of calculating the variance of values within a 2D array in C++. Prior to delving into the practical application of this concept, it is essential to familiarize ourselves with the structure, syntax, and usage of a 2D array in C++, illustrated through examples.

What is the 2D Array?

  • In C++, the most primitive type of multi-dimensional array is a two-dimensional array. It can be visualized as an array of arrays.
  • Another name for a two-dimensional array is a matrix. Depending on the initialization, it can have any type, including integer, character, float, etc.
  • It consists of several Rows and Columns. The defined data value sequence stores every data value in a matrix format.
  • Syntax:

The syntax for declaring a 2D array is:

Example

data_type array_name [x][y];

Where,

x = number of rows.

y = number of columns.

The data_type indicates the kind of information that should be input into the array.

The elements of a 2D array are denoted as arrx, with 'x' indicating the rows and 'y' representing the columns within the array.

Example:

Let's consider an instance to demonstrate the concept of vectors in C++.

Example

#include <iostream>
using namespace std;
void printArray(int arr[][3], int row, int col) {
    for (int i = 0; i < row; ++i) {
        for (int j = 0; j < col; ++j) {
            cout << arr[i][j] << " ";
        }
        cout << endl;
    }
}
int main() {
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int rows = sizeof(arr) / sizeof(arr[0]);
    int cols = sizeof(arr[0]) / sizeof(arr[0][0]);
    printArray(arr, row, col);
    return 0;
}

Output:

What is the Variance?

  • A statistical evaluation of the variation between numbers in a data set is called a variance.
  • Variance measures the extent to which each number in the set deviates from the mean, or average, and consequently from all other numbers in the set.
  • The symbol σ2 is commonly used to represent variance.

We can use the following procedures in C++ to determine the variance of the elements in a 2D array:

  • Determine the array's mean, or average, across all of its elements.
  • Compute the total of the squared deviations between each element and the mean.
  • To find the variance, divide the sum of the squared differences by the total number of elements.
  • Example 1:

Let's consider an illustration to calculate the variance in a two-dimensional array using C++.

Example

#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] = { { 1, 2, 3 }, 
							{ 4, 5, 6 }, 
							{ 7, 8, 9 } }; 

	double result = calculateVariance(rows, cols, matrix); 
	cout << "Variance: " << result << endl; 

	return 0; 
}

Output:

Complexity Analysis:

Time Complexity: O (N*M)

Space Complexity: O (1)

Example 2:

Let's consider another instance to calculate the variation in a two-dimensional array using C++.

Example

#include <iostream>
#include <cmath>
using namespace std;

double calculateMean(int arr[][4], int rows, int cols) {
    double sum = 0;
    int count = 0;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            sum += arr[i][j];
            count++;
        }
    }
    return sum/count;
}
double calculateVariance(int arr[][4], int rows, int cols) {
    double mean = calculateMean(arr, rows, cols);
    double sumSquaredDiff = 0;
    int count = 0;
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            double diff = arr[i][j] - mean;
            sumSquaredDiff += diff * diff;
            count++;
        }
    }
    return sumSquaredDiff / count;
}
int main() {
    int arr[2][4] = {
        {1, 2, 3, 4},
        {5, 6, 7, 8}
    };
    int rows = sizeof(arr) / sizeof(arr[0]);
    int cols = sizeof(arr[0]) / sizeof(arr[0][0]);
    double variance = calculateVariance(arr, rows, cols);
    cout << "Variance: " << variance << endl;
    return 0;
}

Output:

Complexity Analysis:

Time Complexity: O (N*M)

Space Complexity: O (1)

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience