Practical 6- Array and recursion

Posted: January 20, 2012 in Lab 3

Problem Statement-
WAP to calculate the determinant of square matrix of order 3 by 3.

#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#define dim 3
 
int matrix[dim][dim];
 
int determinant(int n, int mat[n][n])
{
	int i,j,i_count,j_count, count=0;
	int array[n-1][n-1], det=0;
 
	if(n<1)
	{
		puts("Error");
		exit(1);
	}
	if(n==1) return mat[0][0];
	if(n==2) return (mat[0][0]*mat[1][1] - mat[0][1]*mat[1][0]);
 
	for(count=0; count<n; count++)
	{
		//Creating array of Minors
		i_count=0;
		for(i=1; i<n; i++)
		{
			j_count=0;
			for(j=0; j<n; j++)
			{
				if(j == count) continue;
				array[i_count][j_count] = mat[i][j];
				j_count++;
			}
			i_count++;
		}
		det += pow(-1, count) * mat[0][count] * determinant(n-1,array);	//Recursive call
	}
	return det;
}
 
int main()
{
	int i,j;
	printf("Enter the elements\n");
	for(i=0;i<3;i++)
		for(j=0;j<3;j++)
			scanf("%d",&matrix[i][j]);
	int x = determinant(dim, matrix);
	printf("Determinant: %d\n", x);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s