C++ Matrix Division Program

Beginner
6 min read
Updated: Oct 2026
2 programs
Live preview

What Is Matrix Division?

Here matrix division means element-wise division: C[i][j] = A[i][j] / B[i][j]. Both matrices need the same shape, and no cell in B may be zero.

Remember
A ÷ B (entrywise) is defined when shapes match and B has no zeros

  [ 8  6 ]   [ 2  3 ]   [ 4.0  2.0 ]
  [ 9  4 ] ÷ [ 3  2 ] = [ 3.0  2.0 ]

Rule: (A ÷ B)[i][j] = A[i][j] / B[i][j]

Note: this is not A × B⁻¹ from linear algebra.
PositionABA / B
[0][0]824.0
[0][1]632.0
[1][0]933.0
[1][1]422.0

How to Divide Matrices in C++

Four clear steps — same nested loops as addition, plus a zero guard.

  1. Confirm both matrices have the same rows and columns.
  2. Reject any zero in B before dividing.
  3. Create a double result matrix of that size.
  4. Set result[i][j] = (double)A[i][j] / B[i][j] for every cell.
MethodIdeaTimeBest for
Nested loopsDivide matching cells into doubleO(m × n)Interviews, teaching
Safe divideValidate shape + no zeros in BO(m × n)Safer production-style code

Pseudocode

Pseudocode
function DivideMatrices(A, B):
    rows = rows of A
    cols = cols of A

    if rows != rows of B or cols != cols of B:
        error "shapes must match"

    C = new double matrix[rows][cols]
    for i from 0 to rows - 1:
        for j from 0 to cols - 1:
            if B[i][j] == 0:
                error "division by zero"
            C[i][j] = A[i][j] / B[i][j]

    return C

Cheat Sheet

Keep these facts handy while writing the program.

TopicDetail
RuleC[i][j] = A[i][j] / B[i][j]
RequirementSame shape; B[i][j] ≠ 0
Result typePrefer double for decimals
Cast(double)a / b avoids integer truncation
Not inverseThis is not A × B⁻¹
Classic check[[8,6],[9,4]] ÷ [[2,3],[3,2]] = [[4,2],[3,2]]

Live Preview

Pick a sample pair to see matrices A, B, and A ÷ B (entrywise).

Tap a chip to run. All samples use nonzero divisors.

Result
A =
8  6
9  4

B =
2  3
3  2

A ÷ B =
4.00  2.00
3.00  2.00

Worked Walkthrough — 2×2

Visit every index once and divide the matching cells.

Calculation
A = [8 6]    B = [2 3]
    [9 4]        [3 2]

i=0, j=0 → 8 / 2 = 4.0
i=0, j=1 → 6 / 3 = 2.0
i=1, j=0 → 9 / 3 = 3.0
i=1, j=1 → 4 / 2 = 2.0

Result = [4.0  2.0]
         [3.0  2.0]

C++ Programs

Start with a clear nested-loop divider using double. Then add shape and zero checks for safer code.

Example 1 — Nested Loops

Divide two same-sized matrices cell by cell into a double result.

C++
#include <iostream>
#include <iomanip>
using namespace std;

void DivideMatrices(int a[][2], int b[][2], double result[][2], int rows, int cols)
{
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            result[i][j] = (double)a[i][j] / b[i][j];
        }
    }
}

void Print(double m[][2], int rows, int cols)
{
    cout << fixed << setprecision(2);
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            cout << m[i][j] << " ";
        }
        cout << endl;
    }
}

int main()
{
    int a[2][2] = { {8, 6}, {9, 4} };
    int b[2][2] = { {2, 3}, {3, 2} };
    double result[2][2];

    DivideMatrices(a, b, result, 2, 2);
    Print(result, 2, 2);
    return 0;
}

How It Works

  1. Pass rows and columns so the loops know the bounds.
  2. Allocate a double result so values can hold decimals.
  3. Outer loop chooses row i; inner loop chooses column j.
  4. Cast a[i][j] to double before / so integer division does not truncate.
  5. Print with fixed and setprecision(2) for two decimal places.

Example 2 — Shape & Zero Safe

Validate matching dimensions and reject any zero divisor before dividing.

C++
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <string>
#include <vector>
using namespace std;

vector<vector<double>> DivideMatrices(const vector<vector<int>>& a,
                                       const vector<vector<int>>& b)
{
    int rows = (int)a.size();
    int cols = rows > 0 ? (int)a[0].size() : 0;

    if ((int)b.size() != rows || (rows > 0 && (int)b[0].size() != cols))
    {
        throw invalid_argument("Matrices must have the same dimensions.");
    }

    vector<vector<double>> result(rows, vector<double>(cols));
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            if (b[i][j] == 0)
            {
                throw runtime_error("B[" + to_string(i) + "][" + to_string(j) + "] is zero.");
            }
            result[i][j] = (double)a[i][j] / b[i][j];
        }
    }
    return result;
}

int main()
{
    vector<vector<int>> a = { {10, 9, 8}, {6, 5, 4} };
    vector<vector<int>> b = { {2, 3, 4}, {2, 1, 2} };
    vector<vector<double>> q = DivideMatrices(a, b);

    cout << fixed << setprecision(2);
    for (int i = 0; i < (int)q.size(); i++)
    {
        for (int j = 0; j < (int)q[i].size(); j++)
        {
            cout << q[i][j] << " ";
        }
        cout << endl;
    }
    return 0;
}

How It Works

  1. Compare both dimensions; throw if shapes differ.
  2. Before each division, check b[i][j] == 0.
  3. Throw runtime_error with the failing index.
  4. Otherwise store (double)a[i][j] / b[i][j].
  5. Mention both checks in interviews — shape and zero are the two traps.

Edge Cases & Pitfalls

Check these before calling the solution done.

Zero in B

Never divide

Guard every B[i][j] before using /.

int / int

Cast to double

Without a cast, 5 / 2 becomes 2, not 2.5.

Shape

Must match

Different sizes cannot be divided entrywise.

Inverse

Different topic

True matrix division via B⁻¹ is not this algorithm.

Time and Space Complexity

ProgramTimeExtra space
Nested loopsO(m × n)O(1) besides result
Shape & zero safeO(m × n)O(1) besides result

Every cell is touched exactly once. The result matrix needs O(m × n) space.

Key Takeaways

  • Rule: divide matching cells; shapes must match.
  • Guard: never divide by a zero in B.
  • Type: use double and cast before /.
  • Test: [[8,6],[9,4]] ÷ [[2,3],[3,2]] → [[4,2],[3,2]].

One line: same shape, nonzero B — then C[i][j] = A[i][j] / B[i][j].

Frequently Asked Questions

Element-wise division: result[i][j] = A[i][j] / B[i][j]. Both matrices must have the same shape, and B must not contain zeros.
Usually not. In higher math, matrix division often means multiplying by an inverse. This page uses simpler cell-by-cell division.
Division often produces decimals (for example 5 / 2 = 2.5). A double result keeps fractional values visible.
Division by zero is invalid. Check B first and throw (or skip) before dividing.
For an m × n matrix, each cell is visited once, so time is O(m × n).

Next: Matrix Multiplication

Multiply matrices with row-column dot products.

Matrix multiplication tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful