 # C++ Programming Code Examples

## C++ > Computer Graphics Code Examples

### Compute the Volume of a Tetrahedron Using Determinants

``` Compute the Volume of a Tetrahedron Using Determinants This is a C++ Program to find the volume of tetrahedron. Call the four vertices of the tetrahedron (a, b, c), (d, e, f), (g, h, i), and (p, q, r). Now create a 4-by-4 matrix in which the coordinate triples form the colums of the matrix, with a row of 1's appended at the bottom: a d g p b e h q c f i r 1 1 1 1 The volume of the tetrahedron is 1/6 times the absolute value of the matrix determinant. For any 4-by-4 matrix that has a row of 1's along the bottom, you can compute the determinant with a simplification formula that reduces the problem to a 3-by-3 matrix a-p d-p g-p b-q e-q h-q c-r f-r i-r #include<stdio.h> #include<stdlib.h> #include<iostream> #include<math.h> using namespace std; double det(int n, double mat) { double submat; float d; for (int c = 0; c < n; c++) { int subi = 0; //submatrix's i value for (int i = 1; i < n; i++) { int subj = 0; for (int j = 0; j < n; j++) { if (j == c) continue; submat[subi][subj] = mat[i][j]; subj++; } subi++; } d = d + (pow(-1, c) * mat[c] * det(n - 1, submat)); } return d; } int main(int argc, char **argv) { cout << "Enter the points of the triangle:\n"; int x1, x2, x3, x4, y1, y2, y3, y4, z1, z2, z3, z4; cin >> x1; cin >> x2; cin >> x3; cin >> x4; cin >> y1; cin >> y2; cin >> y3; cin >> y4; cin >> z1; cin >> z2; cin >> z3; cin >> z4; double mat; mat = x1; mat = x2; mat = x3; mat = x4; mat = y1; mat = y2; mat = y3; mat = y4; mat = z1; mat = z2; mat = z3; mat = z4; mat = 1; mat = 1; mat = 1; mat = 1; cout << "\nMatrix formed by the points: \n"; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { cout << mat[i][j] << " "; } cout << endl; } double matrix; matrix = x1 - x4; matrix = x2 - x4; matrix = x3 - x4; matrix = y1 - y4; matrix = y2 - y4; matrix = y3 - y4; matrix = z1 - z4; matrix = z2 - z4; matrix = z3 - z4; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cout << matrix[i][j] << " "; } cout << endl; } float determinant = det(3, matrix) / 6; if (determinant < 0) cout << "The Area of the tetrahedron formed by (" << x1 << "," << y1 << "," << z1 << "), (" << x2 << "," << y2 << "," << z2 << "), (" << x3 << "," << y3 << "," << z3 << "), (" << x4 << "," << y4 << "," << z4 << ") = " << (determinant * -1); else cout << "The Area of the tetrahedron formed by (" << x1 << "," << y1 << "," << z1 << "), (" << x2 << "," << y2 << "," << z2 << "), (" << x3 << "," << y3 << "," << z3 << "), (" << x4 << "," << y4 << "," << z4 << ") = " << determinant; return 0; } ```