hey,
I'm trying to code a program that will accept a text file input for the dimension and elements of a matrix and store that to an array. Then the program will calculate the determinate of the matrix and output it to both the console and a file. I'm having problems specifically with storing the text file to an array and calculating the determinate.

here is what i have so far:

// This program evaluates determinants of square matrices using minors.
//
// The program can handle up to nine by nine square matrices.
//
// This program reads input from a file and writes identical output to
// both the console and to a file.
//
// The program reads a matrix dimension and the required number of matrix
// elements, writes the matrix in columns, calculates the determinant,
// and writes the value of the determinant.  The process repeats until
// an end of file is encountered or an invalid dimension is specified.
//
// After each determinant value is written a blank line is written.
//
// After all processing is completed, the termination message "Done."
// is written.
//
// If the input or output file cannot be opened, the program terminates without
// any other action than displaying an error message.

// Examples
//
// DETERMINANT EVALUATOR
//
// Matrix dimension:2
//
// Input values:
// 4.0000
// -3.0000
// 2.0000
// 6.0000
//
// Matrix:
//     4.0000   -3.0000
//     2.0000    6.0000
//
// Determinant value:30.0000
//
// Matrix dimension:4
//
// Input values:
// 0.1000
// 1.3000
// -3.5000
// 2.8000
// 1.7000
// -3.5000
// 2.4000
// -4.1000
// 2.3000
// 0.0000
// -1.6000
// 3.9000
// 1.2000
// -2.7000
// -0.5000
// 1.0000
//
// Matrix:
//     0.1000    1.3000   -3.5000    2.8000
//     1.7000   -3.5000    2.4000   -4.1000
//     2.3000    0.0000   -1.6000    3.9000
//     1.2000   -2.7000   -0.5000    1.0000
//
// Determinant value:-72.8371
//
// Done.


 
//#define SHOW_DETERMINANTS


#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
using namespace std;


//  **************************************************************************
//  *                                                                        *
//  *                            GLOBAL CONSTANTS                            *
//  *                                                                        *
//  *************************************************************************

	const string INFILE_NAME  = "File4.In";
	const string OUTFILE_NAME = "File4.Out";

	const int MAX_DIM         = 9;		// Maximum matrix dimension
	const int PRECISION       = 4;		// Precision of double output
	const int OUTPUT_WIDTH    = 10;		// Width of double output


//  **************************************************************************
//  *                                                                        *
//  *                            GLOBAL VARIABLES                            *
//  *                                                                        *
//  **************************************************************************

    ifstream fin;						// Input file
    ofstream fout;						// Output file
	bool    ineof;						// End of file indicator
	int dimension;
	int det;
	int row, column;
	double minor;



// Function declarations
bool	initialize();				// Initialize the program

bool	getInput					// Get the input matrix
		(double  mat[][MAX_DIM],	// Matrix
		 int    &dim);				// Matrix dimension

void	displayMatrix				// Display the matrix
	    (double  mat[][MAX_DIM],	// Matrix
		 int     dim);				// Matrix dimension

double	evaluate					// Evaluate a determinant
	    (double  mat[][MAX_DIM],	// Matrix
		 int     dim);				// Matrix dimension

void	finish();					// Terminate the program

bool	process1;					// Processing indicator
bool	process2;					// Processing indicator

int     size;						// Matrix dimension

double  answer;						// Value of determinant
double  mat[MAX_DIM][MAX_DIM];		// Matrix

int calcminor(double mat[][MAX_DIM], minor, int row, int column);

int calcdet(det *a) {
       int result=0;
       matrix minor;

       if(dimension < 1)
         return 0;
	   if(dimension == 1) {    // stopping condition
         return mat[0][0];     //returns 0,0 element
	   }
	   for(int i=0; i < dimension; i++){ 
          if(!calcminor(a,&minor,0,i))
             return 0;
          result += ( pow(-1,i) * mat[0][i] * calcdet(&minor));
     }
       return result;
}

//  **************************************************************************
//  *                                                                        *
//  *                              MAIN PROGRAM                              *
//  *                                                                        *
//  **************************************************************************

int main()
{
	// Initialize
	process1 = initialize();

	// If the files were opened successfully
	if (process1)
	{
		// Do
		do
		{
			// Get the input equations
			process2 = getInput(mat, size);

			// If the input is valid
			if (process2)
			{
				// Display the matrix
				displayMatrix(mat, size);

				// Evaluate the determinant
				answer = evaluate(mat, size);

				// Report the value of the determinant
				cout << "Determinant value:" << answer << endl;
				fout << "Determinant value:" << answer << endl;

				// Write a blank line
				cout << endl;
				fout << endl;
			}
		}
		// While the input is valid
		while (process2);

		// Finish
		finish();
	}

	// Return
	return 0;
}


 
//  **************************************************************************
//  *                                                                        *
//  *                          INITIALIZE FUNCTION                           *
//  *                                                                        *
//  **************************************************************************

bool	initialize()					// Initialize program
{
	bool	success;					// Initialization success indicator


	// Set the success indicator false
	success = false;

	// Initialize the end of file false
	ineof  = false;

	// Open the input file
	fin.open(INFILE_NAME.c_str(), ios::in);

	// If the file was not opened successfully
	if (!fin)
	{
		// Set the end of file indicator true
		ineof = true;

		// Display an error message
		cout << "ERROR:  Unable to open input file \"" 
			 << INFILE_NAME << "\"" << endl;
	}

	// Else
	else
	{
		// Open the output file
		fout.open(OUTFILE_NAME.c_str(), ios::out);

		// If the output file was not opened successfully
		if (!fout)
		{
			// Set the end of file indicator true
			ineof = true;

			// Close the input file
			fin.close();

			// Display an error message
			cout << "ERROR:  Unable to open output file \"" 
				 << OUTFILE_NAME << "\"" << endl;
		}
	}
	// If there is valid input
	if (!ineof)
	{
		// Set the success indicator true
		success = true;

		// Set the output format
		cout.setf(ios::fixed);
		cout.setf(ios::showpoint);
		cout.precision(PRECISION);
		fout.setf(ios::fixed);
		fout.setf(ios::showpoint);
		fout.precision(PRECISION);

		// Display a title
		cout << "DETERMINANT EVALUATOR" << endl;
		fout << "DETERMINANT EVALUATOR" << endl;

		// Display a blank line
		cout << endl;
		fout << endl;
	}

	// Return the initialization success
	return success;
}

 
//  **************************************************************************
//  *                                                                        *
//  *                           GET INPUT FUNCTION                           *
//  *                                                                        *
//  **************************************************************************

bool	getInput						// Get the input matrix
		(double  mat[][MAX_DIM],		// Matrix
		 int    &dim)					// Matrix dimension
{
	bool	valid;						// Valid input indicator
	int		r;							// Row    number
	int		c;							// Column number

	valid = false;// Set the valid input indicator false
	fin >> dimension;// Get the matrix dimension
	if (dimension <= 9) {// If the input is good
		cout << "Matrix dimension:" << dimension << endl;// Display a header for the matrix dimension
		// Echo the input
		cout << endl;// Display a blank line
	}
		if (dimension < 2) {// If the dimension is less than 2
			cerr << "Error: Matrix dimension too small." << endl;// Display an error message
		}// Display a blank line
		else if (dimension > 9) {// Else if the dimension is too large
			cerr << "Error: Matrix dimension too large." << endl;// Display an error message
		}// Display a blank line
		else {// Else
			cout << "Input values:";// Display a header for the input values
			for (r = 0; r < (dimension -1); r++) {
				for (c = 0; c < (dimension - 1); c++) {// Enter the data for each row
					fin >> mat[r][c];// Enter the data for one row
						// Get one matrix element
							// If the input is good
							cout << mat[r][c];// Echo the value
				}
			}
			// If the input is all good
				valid = true;// Set the valid input indicator true
			cout << endl;// Display a blank line
		}
	// Return the result
	return valid;
}

 
 
//  **************************************************************************
//  *                                                                        *
//  *                        DISPLAY MATRIX FUNCTION                         *
//  *                                                                        *
//  **************************************************************************

void	displayMatrix					// Display the matrix
		(double  mat[][MAX_DIM],		// Matrix
		 int     dim)					// Matrix dimension
{
	int		r;							// Row    number
	int		c;							// Column number


	cout << "Matrix:" << endl;// Display a matrix header
	for (r = 0; r < dimension; r++) {// Display all rows
		for (c = 0; c < dimension; c++) {// Display one row
			cout << mat[r][c];// Display one matrix element
		cout << endl;// End the line
		}
	}
	cout << endl;// Display a blank line
}

 
 
//  **************************************************************************
//  *                                                                        *
//  *                      EVALUATE DETERMINANT FUNCTION                     *
//  *                                                                        *
//  **************************************************************************

double	evaluate						// Evaluate a determinant
		(double  mat[][MAX_DIM],		// Matrix
		 int     dim)					// Matrix dimension
{
       int result=0;
       matrix;
	   minor;
	   int i, j;

       if(dimension < 1)
         return 0;

       if(dimension == 1)      // stopping condition
         return mat[0][0];     //returns 0,0 element

       for(int i = 0; i < dimension; i++) {
          if(!calcminor(det, &minor, 0, i))
             return 0;
          result+=( pow(-1,i)*mat[0][i]*calcdet(&minor));
     }

       return result;
}


 
//  **************************************************************************
//  *                                                                        *
//  *                            FINISH FUNCTION                             *
//  *                                                                        *
//  **************************************************************************

void	finish()						// Terminate the program
{
	// Display a termination message
	cout << "Done." << endl;
	fout << "Done." << endl;

	// Close the input file
	fin.close();

	// Close the output file
	fout.close();
}


 
//  **************************** SUPPORT FUNCTION ****************************


//  **************************************************************************
//  *                                                                        *
//  *                      DISPLAY DETERMINANT FUNCTION                      *
//  *                                                                        *
//  **************************************************************************

void	displayDeterminant				// Display a determinant
		(double  mat[][MAX_DIM],		// Matrix
		 int     dim,					// Matrix dimension
		 double  det)					// Value of determinant
{
	int		r;							// Row    number
	int		c;							// Column number

	// Display a matrix header
	cout << "Determinant:" << endl;
	fout << "Determinant:" << endl;

	// Display all rows
	for (r = 0; r < dim; r++)
	{
		// Display an initial bar
		cout << "| ";
		fout << "| ";

		// Display one row
		for (c = 0; c < dim; c++)
		{
			// Display one matrix element
			cout << setw(OUTPUT_WIDTH) << mat[r][c];
			fout << setw(OUTPUT_WIDTH) << mat[r][c];
		}

		// Display a terminal bar
		cout << " |";
		fout << " |";

		// End the line on the console
		cout << endl;
		fout << endl;
	}

	// Display a blank line
	cout << endl;
	fout << endl;

	// Display the determinant value
	cout << "Subdeterminant value:" << det << endl;
	fout << "Subdeterminant value:" << det << endl;

	// Display a blank line
	cout << endl;
	fout << endl;
}


calcminor(mat, minor, int& row,int& column) {
       int p = 0,q = 0;
	   if(dimension <= 1) {
		   return 0;
	   }
	   if(!create(minor, dimension - 1)) {
		   return 0;
	   }
       for(int i=0; i < dimension; i++)
         if(i!= row){
           q=0;
         for(int j=0; j < dimension;j++)
           { if(j!=column)
           minor->mat[p][q]=mat[i][j];
           q++;
           }
        p++;
     }
     return 1;
}

I am using Visual Studio C++ 2005 express edition. Here is the build log:
1>------ Build started: Project: Matrix Evaluator, Configuration: Debug Win32 ------
1>Compiling...
1>matrix evaluator.cpp
1>.\matrix evaluator.cpp(139) : error C2061: syntax error : identifier 'minor'
1>.\matrix evaluator.cpp(141) : error C2065: 'a' : undeclared identifier
1>.\matrix evaluator.cpp(141) : error C2448: 'calcdet' : function-style initializer appears to be a function definition
1>.\matrix evaluator.cpp(372) : error C2065: 'matrix' : undeclared identifier
1>.\matrix evaluator.cpp(383) : error C2660: 'calcminor' : function does not take 4 arguments
1>.\matrix evaluator.cpp(385) : error C2668: 'pow' : ambiguous call to overloaded function
1> C:\Program Files\Microsoft Visual Studio 8\VC\include\math.h(575): could be 'long double pow(long double,int)'
1> C:\Program Files\Microsoft Visual Studio 8\VC\include\math.h(527): or 'float pow(float,int)'
1> C:\Program Files\Microsoft Visual Studio 8\VC\include\math.h(489): or 'double pow(double,int)'
1> while trying to match the argument list '(int, int)'
1>.\matrix evaluator.cpp(385) : error C3861: 'calcdet': identifier not found
1>.\matrix evaluator.cpp(473) : error C2062: type 'int' unexpected
1>.\matrix evaluator.cpp(473) : error C2143: syntax error : missing ';' before '{'
1>.\matrix evaluator.cpp(473) : error C2447: '{' : missing function header (old-style formal list?)
1>Matrix Evaluator - 10 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Thanks in advance for any help.

Recommended Answers

All 2 Replies

Start at the top. Fix the first error. Compile. Lather, rinse, repeat until no errors or warnings.

  *** {BD Software Proxy c++ v3.43a for gcc} STL Message Decryption is ON! ***
main.cpp:139: error: `minor' is not a type
main.cpp:139: error: ISO C++ forbids declaration of `parameter' with no type
main.cpp:141: error: `a' was not declared in this scope
main.cpp:141: error: expected `, ' or `;' before '{
        ' token
main.cpp: In function `double evaluate(double (*)[9], int)':
main.cpp:372: error: `matrix' undeclared (first use this function)
main.cpp:383: error: invalid conversion from `int' to `double (*)[9]'
main.cpp:383: error:   initializing argument 1 of 
   `int calcminor(double (*)[9], int, int, int)'
main.cpp:383: error: invalid conversion from `double *' to `int'
main.cpp:383: error:   initializing argument 2 of 
   `int calcminor(double (*)[9], int, int, int)'
main.cpp:385: error: `calcdet' cannot be used as a function
main.cpp: At global scope:
main.cpp:473: error: expected constructor, destructor, or type conversion
    before '(
        ' token
main.cpp:473: error: expected `, ' or `;' before '(
        ' token

And, save yourself and others who read the code a lot of time and confusion by not putting in redundant, uninformative comments:

valid = false;// Set the valid input indicator false
    fin >> dimension;// Get the matrix dimension
    if (dimension <= 9) {// If the input is good

When you use good, descriptive variable and function names (as you mostly have), such comments serve no purpose, take up time, make editing harder, and create visual clutter.

Specific to the problem you stated, reading in the data, your code says:

for (r = 0; r < (dimension -1); r++) {
            for (c = 0; c < (dimension - 1); c++) {// Enter the data for each row
                fin >> mat[r][c];// Enter the data for one row
                // Get one matrix element

You are stopping one short of the number of rows and columns. If the dimension value is 4, then you need to read into rows 0, 1, 2, 3, and into columns 0, 1, 2, 3. Stopping at r < ( dimension -1 ) only gets row/columns 0, 1, 2.
Correct version would be:

for ( r = 0; r < dimension ; r++ ) 
        {
            for ( c = 0; c < dimension ; c++ ) 
            {
                fin >> mat[r][c];
                cout << mat[r][c];
            }
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.