Thread: matrix determinant

  1. #1
    Registered User
    Join Date
    Jun 2009
    Location
    US of A
    Posts
    305

    Question matrix determinant

    I am writing a program to calculate the determinant of an n*n matrix. The issue is that the program ends abruptly without giving any error and does not return the result of the determinant. I am using Visual Studio c++ 2008 for the same. The code for the calculation of the matrix determinant is as follows:

    insert
    Code:
    #include <stdio.h>
    #include <conio.h>
    #include <stdlib.h>
    
    int detmat(int *, int);
    
    main(){
    
    	int* arr, i,j;
    	int result = 0, num, n=0, pos;
    
    
    	printf("\n\rEnter the order of matrix");
    	scanf("%d", &n);
    	arr = calloc(n*n, 2);
    
    	printf("Enter the elements");
    	for(i =0;i<n;i++){
    		for(j =0;j<n;j++){
    			scanf("%d", &num);
    			pos = i*n+j;
    			arr[pos] = num;
    		}
    	}
    
    	//print the matrix
    
    	for(i=0;i<n;i++){
    		for(j=i;j<n*n; j+= n){
    			printf("\t%d", arr[j]);
    		}
    		printf("\n\r");
    	}
    
    	result = detmat(arr, n);
    	free(arr);
    
    	printf("\n %d", result);
    
    	printf("\n\n\nPress any key to exit");
    	getch();
    
    }
    
    int detmat(int *arr, int order){
    
    	int *arr2, i,j,k, sign=1;
    	int pos, newpos, count, sum =0;
    
    	if(order == 1)
    		return (arr[0]);
    
    	for(i=0;i<order;i++, sign *= -1){
    
    		arr2 = calloc((order-1)*(order-1),2);
    
    		for(j=1;j<order;j++){			
    			for(k=0,count =0;k < order;k++){
    
    				if(k == i)
    					continue;
    
    				pos = j*order+k;
    				newpos = (j-1)*(order-1) + count;
    				arr2[newpos] = arr[pos];
    				count++;
    			}
    
    		}
    
    		sum = sum + arr[i]*sign*detmat(arr2, order-1);
    		free(arr2);
    	}
    
    	return (sum);
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > arr = calloc(n*n, 2);
    Try sizeof(int) rather than 2

    But then you did just copy/paste this from some TurboC user from about 20 years ago.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C - access violation
    By uber in forum C Programming
    Replies: 2
    Last Post: 07-08-2009, 01:30 PM
  2. Matrix Help
    By HelpmeMark in forum C++ Programming
    Replies: 27
    Last Post: 03-06-2008, 05:57 PM
  3. Very handy matrix functions - part 1
    By VirtualAce in forum Game Programming
    Replies: 8
    Last Post: 05-20-2004, 10:38 AM
  4. Matrix and vector operations on computers
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 05-11-2004, 06:36 AM