Knowledge is the key to immortality
Some Programs in C - Part 8
Prepared by Ratul Chakraborty - Assistant Professor - Statistics

Some Programs in C - Part 8

 

Determinant of square matrix by Pivotal Condensation method

The Program

#include <stdio.h>
#include <math.h>

#define MAX_ORDER 20

double det(double [][], int);

int main()
{
	int i, j, n;
	double M[MAX_ORDER][MAX_ORDER];     

	printf("ORDER OF SQUARE MATRIX (ROW = COLUMN) : ");
	scanf("%d",&n);

	if(n < 1 || n > 20){
		printf("\nORDER OF SQUARE MATRIX MUST BE >= 1 & <= 20");
		return 0;
	}
    
	printf("\nINPUT MATRIX ROW-WISE\n\n");
	for(i=0; i<n; i++){
		printf("ROW-%d : ",i+1);
		for(j=0; j<n; j++)
			scanf("%lf", &M[i][j]);
	}
    
	printf("\nDETERMINANT = %g", det(M,n));
    
	return 0;
}

double det(double A[][MAX_ORDER], int n)
{
	int i, k, j, bigi;
	double D = 1, sum = 0, ratio, big, temp; 

	for(i=0; i<n; i++){
		big = fabs(A[i][i]);
		bigi = i;
		for(k=i+1; k<n; k++){
			if(big < fabs(A[k][i])){
				big = fabs(A[k][i]);
				bigi = k;
			}
		}
		if(big == 0.0)return 0.0;
		if(bigi > i){
			for(j=i; j<n; j++){
				temp = A[bigi][j]; 
				A[bigi][j] = A[i][j]; 
				A[i][j] = temp;
			}
			D = -D;
		}
		temp = A[i][i]; 
		if(temp < 0.0){
			D *= -1.0;
			sum += log(-temp); 
		}
		else sum += log(temp); 
		for(k=i+1; k<n; k++)
		{
			ratio = A[k][i]/temp;
			for(j=i; j<n; j++)
				A[k][j] = A[k][j] - A[i][j] * ratio;
		}
	}
	return (D<0)? -exp(sum) : exp(sum);
}

Output

ORDER OF SQUARE MATRIX (ROW = COLUMN) : 5

INPUT MATRIX ROW-WISE

ROW-1 : 10      20      30      40      50
ROW-2 : 12      -4      0       3       10
ROW-3 : 5       5       7       1       0
ROW-4 : 0       0       1       2       5
ROW-5 : 3       1       5       7       7

DETERMINANT = 20370
Copyright © 2018 - All Rights Reserved - www.mbbcollege.in