REM  PROGRAM    invdet.bas
REM      BY S. NARASIMHAN, 16, SATHYA NAGAR, MADURAI-625018. INDIA
REM ==============================================================
REM  PROGRAM TO FIND THE INVERSE , DETERMINANT OF A SQUARE MATRIX
REM    USES FULL PIVOTING
REM ==============================================================
REM  MAXIMUM SIZE/ORDER OF MATRIX SUPPORTED IS 40.
REM ==============================================================
DIM A(40,40), P(40), B(40,2)
MAXSIZE = 40
L = LEN(COMMAND$)
IF L = 0 THEN
   GOTO 1000
ELSE  'Parse the Command Line
   FOR I = 1 TO L
     CH$ = UCASE$(MID$(COMMAND$,I,1))
     IF CH$ = "I" THEN OPT = 1 : EXIT FOR
     IF CH$ = "D" THEN OPT = 2 : EXIT FOR
     OPT = 0
   NEXT
   IF OPT = 0 THEN GOTO 1000
END IF
CORRECT = 0
WHILE NOT CORRECT
  INPUT "Order of the Matrix:", N
  IF N > MAXSIZE THEN
     PRINT USING "Order should be Maximum ###"; MAXSIZE
  ELSEIF N <= 0 THEN
     PRINT "Size should be positive non-zero"
  ELSEIF N <> INT(N) THEN
     PRINT "Size should be a whole number"
  ELSE
     CORRECT = 1
  END IF
WEND
REM GET THE MATRIX
PRINT "Enter the Matrix(One Element per line)"
FOR I = 1 TO N
  PRINT USING "**********ROW = ###**********"; I
  FOR J = 1 TO N
    INPUT A(I,J)
  NEXT  'J
  PRINT
NEXT   'I
REM INITIALIZATION
D = 1
FOR I = 1 TO N
   P(I) = 0
NEXT

REM SEARCH FOR PIVOT
FOR J = 1 TO N
   T = 0
   FOR K = 1 TO N
     IF P(K) <> 1 THEN
       FOR L = 1 TO N
         IF P(L) <> 1 THEN
           IF P(L) > 1 THEN 430
           IF ABS(T) < ABS(A(K,L)) THEN R = K : C = L : T = A(K,L)
         END IF
       NEXT
    END IF
    NEXT
    P(C) = P(C) + 1
   ' PUT THE PIVOT ON DIAGONAL
    IF R <> C THEN
      D = -D
      FOR K = 1 TO N
        SWAP A(R,K), A(C,K)
      NEXT
    END IF
    B(J,1) = R : B(J,2) = C
    T1 = A(C,C) : D = D * T1
    ' DIVIDE PIVOT ROW PIVOT ELEMENT
    A(C,C) = 1
    FOR L = 1 TO N
      A(C,L) = A(C,L) / T1
    NEXT
    ' REDUCE NON-PIVOT ROWS
    FOR K = 1 TO N
      IF K <> C THEN
        T = A(K,C) : A(K,C) = 0
        FOR L = 1 TO N
          A(K,L) = A(K,L) - A(C,L) * T
        NEXT   'L
      END IF
    NEXT     'K
NEXT  'J
430:
IF OPT = 2 THEN  'DETERMINANT OPTION
  PRINT : PRINT USING "DETERMINANT= ######.##"; D
  END
END IF
REM INVERSE OPTION - INTERCHANGE COLUMNS
FOR I = 1 TO N
  L = N - I + 1
  IF B(L,1) <> B(L,2) THEN
    R = B(L,1) : C = B(L,2)
    FOR K = 1 TO N
       SWAP A(K,R), A(K,C)
    NEXT  'K
  END IF
NEXT  'I
REM PRINT THE INVERSE
PRINT : PRINT "**********INVERSE***************"
FOR I = 1 TO N
  PRINT USING "***********ROW =### ********"; I
  FOR J = 1 TO N
     PRINT USING "#####.##"; A(I,J)
  NEXT  'J
  PRINT
NEXT  'I
END

REM PRINT USAGE FOR THE PROGRAM & DIE
1000   PRINT "Usage : invdet option"
PRINT "    option = I ===> To find Matrix Inverse"
PRINT "    option = D ===> To find the determinant"
END
