I am writing code to read in a set of numbers and then display them in a 4x4 grid on screen, the program will then determine if it is a magic square. My question is how can I get the user to input the numbers into a file that is shown in the readData method so that when that method is called it will display the users grid.
Also where does the file data.txt get stored?
thanks
#include<iostream>
#include<fstream>
using namespace std;
const int dimension = 4; // dimension for the array
typedef int Sq[dimension] [dimension]; // declare vector for type names
void ReadData(Sq square ) // read data from file
{ ifstream inFile;
char fileName[13] = "data.txt";
inFile.open (fileName); // open file for reading
for (int r = 0; r < dimension; r++) // row loop
for ( int c = 0; c < dimension; c++) // column loop
inFile >> square[r][c]; // read data into matrix
inFile.close( ); // close the file
}
void Display ( const Sq square ) // display matrix
{ cout << " Magic Square Program " << endl << endl;
for (int r = 0; r < dimension; r++)
{ for ( int c = 0; c < dimension; c++)
{ cout.width(6); //set output width to 6 characters
cout << square[r][c] << "\t "; // display numbers
}
cout << endl;
}
}
bool magicSquare( Sq square) // add rows, columns, and diagonals
{ int firstSum = 0, sum;
bool magic = true;
for (int r = 0; r < dimension; r++) // add 1st column for a comparison
firstSum += square[r][1];
for (int r = 1; r < dimension; r++) // row loop first when adding rows
{ sum = 0;
for ( int c = 0; c < dimension; c++)
sum += square[r][c]; // add row
if ( sum != firstSum) // check for magic failure
return (false); // not magic
}
for ( int c = 0; c < dimension; c++) // column loop first when adding columns
{ sum = 0;
for (int r = 0; r < dimension; r++)
sum += square[r][c]; // add columns
if ( sum != firstSum) // check for magic failure
return (false); // not magic
}
sum = 0;
for (int r = 0; r < dimension; r++)
sum += square[r][r]; // add front diagonal
if ( sum != firstSum) // check for magic failure
return (false); // not magic
sum = 0;
for (int r = 0; r < dimension; r++)
sum += square[r][dimension - r - 1]; // add back diagonal
if ( sum != firstSum) // check for magic failure
return (false); // not magic
else
return (true);
} // end magicSquare function
int main( )
{
Sq square;
ReadData( square); // read data from file
Display ( square); // display matrix
if ( magicSquare(square) ) // check for magic property
cout << "\n This Square is Magic \n " << endl;
else
cout << "\n This Square is Not Magic \n " << endl;
system("Pause");
return(0);
}
The easiest way is to make the program take the filename as a command-line argument. Main should really look like this, where argc is the number of arguments, and argv[] is and array of char pointers to them (argv[0] is always the name of the executable). See What does int argc, char *argv[] mean?
int main(int argc, char * argv[])
So then, you do
if (argc == 2)
{
ReadData(square, argv[1]);
...
}
else
...
And ReadData would look like this:-
void ReadData(Sq &square, const std::string &filename) // read data from file
{
ifstream inFile;
inFile.open (filename); // open file for reading
NOTE! you need to take square as a reference parameter (&square) otherwise your input data just gets ignored.
My question is how can I get the user to input the numbers into a file that is shown in the readData method?
Ask politely? Since it's a file on the disk, user has to fill it before the program starts. You could use appropriate ifstream flag to not create the file if it doesn't exist, and display an error message instead, terminating the program afterwards.
Also where does the file data.txt get stored?
In the current execution path of the binary. This may or may not be the folder where the binary is located.
As a side note, as you are using C++, std::array<> might be a better fit than C-style arrays.
Related
The following C++ program takes two text files, stop_words.txt, and story.txt. It then removes all the stop word occurrences in the story.txt file. For instance,
Monkey is a common name that may refer to groups or species of mammals, in part, the simians of infraorder L. The term is applied descriptively to groups of primates, such as families of new world monkeys and old world monkeys. Many monkey species are tree-dwelling (arboreal), although there are species that live primarily on the ground, such as baboons. Most species are also active during the day (diurnal). Monkeys are generally considered to be intelligent, especially the old world monkeys of Catarrhini.
the text above is story.txt, and the stop_words.txt file is given below:
is
are
be
When I run my code, it doesn't delete all the stop words and keeps some of them. The code also creates a file called stop_words_counter.txt which should display the number of stop word occurrences like so:
is 2
are 4
b 1
But my output file shows the following:
is 1
are 4
be 1
I would be very grateful for some help regarding this code! I have posted it below for your reference.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
const int MAX_NUM_STOPWORDS = 100;
struct Stop_word
{
string word; // stop word
int count; // removal count
};
int stops[100];
string ReadLineFromStory(string story_filename )
{
string x = "";
string b;
ifstream fin;
fin.open(story_filename);
while(getline(fin, b))
{
x += b;
}
return x;
}
void ReadStopWordFromFile(string stop_word_filename, Stop_word words[], int &num_words)
{
ifstream fin;
fin.open(stop_word_filename);
string a;
int i = 0;
if (fin.fail())
{
cout << "Failed to open "<< stop_word_filename << endl;
exit(1);
}
words[num_words].count = 0;
while (fin >> words[num_words].word)
{
++num_words;
}
fin.close();
}
void WriteStopWordCountToFile(string wordcount_filename, Stop_word words[], int num_words)
{
ofstream fout;
fout.open(wordcount_filename);
for (int i = 0; i < 1; i++)
{
fout << words[i].word << " "<< stops[i] + 1 << endl;
}
for (int i = 1; i < num_words; i++)
{
fout << words[i].word << " "<< stops[i] << endl;
}
fout.close();
}
int RemoveWordFromLine(string &line, string word)
{
int length = line.length();
int counter = 0;
int wl = word.length();
for(int i=0; i < length; i++)
{
int x = 0;
if(line[i] == word[0] && (i==0 || (i != 0 && line[i-1]==' ')))
{
for(int j = 1 ; j < wl; j++)
if (line[i+j] != word[j])
{
x = 1;
break;
}
if(x == 0 && (i + wl == length || (i + wl != length && line[i+wl] == ' ')))
{
for(int k = i + wl; k < length; k++)
line[k -wl] =line[k];
length -= wl;
counter++;
}
}
}
line[length] = 0;
char newl[1000] = {0};
for(int i = 0; i < length; i++)
newl[i] = line[i];
line.assign(newl);
return counter;
}
int RemoveAllStopwordsFromLine(string &line, Stop_word words[], int num_words)
{
int counter[100];
int final = 0;
for(int i = 1; i <= num_words; i++)
{
counter[i] = RemoveWordFromLine(line, words[i].word);
final += counter[i];
stops[i] = counter[i];
}
return final;
}
int main()
{
Stop_word stopwords[MAX_NUM_STOPWORDS]; // an array of struct Stop_word
int num_words = 0, total = 0;
// read in two filenames from user input
string a, b, c;
cin >> a >> b;
// read stop words from stopword file and
// store them in an array of struct Stop_word
ReadStopWordFromFile(a, stopwords, num_words);
// open text file
c = ReadLineFromStory(b);
// open cleaned text file
ofstream fout;
fout.open("story_cleaned.txt");
// read in each line from text file, remove stop words,
// and write to output cleaned text file
total = RemoveAllStopwordsFromLine(c, stopwords, num_words) + 1 ;
fout << c;
// close text file and cleaned text file
fout.close();
// write removal count of stop words to files
WriteStopWordCountToFile("stop_words_count.txt", stopwords, num_words);
// output to screen total number of words removed
cout << "Number of stop words removed = " << total << endl;
return 0;
}
There is one major bug in your code.
in function RemoveAllStopwordsFromLine
you are using the wrong array indices. In C++ the first element in an array has the index 0. Also you must compare with "less" than the size.
for (int i = 1; i <= num_words; i++)
So the first stop word "is", will never be checked and counted.
Please modify to
for (int i = 0; i < num_words; i++)
But then you need also to remove your patch in function WriteStopWordCountToFile . You made a special case for element 0. That is wrong.
Please remove
for (int i = 0; i < 1; i++)
{
fout << words[i].word << " " << stops[i] + 1 << endl;
}
and start the next for with 0. And remove the "+" while calculating the total.
Because you are using C-Style arrays, magic numbers and ultra complex code, I will show you a modern C++ solution.
In C++ you have many useful algorithms. Some are specifically designed to address your requirments. So, please use them. Try to get away from C and migrate to C++.
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
#include <regex>
#include <sstream>
// The filenames. Whatever you want
const std::string storyFileName{ "r:\\story.txt" };
const std::string stopWordFileName{ "r:\\stop_words.txt" };
const std::string stopWordsCountFilename{ "r:\\stop_words_count.txt" };
const std::string storyCleanedFileName{ "r:\\story_cleaned.txt" };
// Becuase of the simplicity of the task, put everything in main
int main() {
// Open all 4 needed files
std::ifstream storyFile(storyFileName);
std::ifstream stopWordFile(stopWordFileName);
std::ofstream stopWordsCountFile(stopWordsCountFilename);
std::ofstream storyCleanedFile(storyCleanedFileName);
// Check, if the files could be opened
if (storyFile && stopWordFile && stopWordsCountFile && storyCleanedFile) {
// 1. Read the complete sourcefile with the story into a std::string
std::string story( std::istreambuf_iterator<char>(storyFile), {} );
// 2. Read all "stop words" into a std::vector of std::strings
std::vector stopWords(std::istream_iterator<std::string>(stopWordFile), {});
// 3. Count the occurences of the "stop words" and write them into the destination file
std::for_each(stopWords.begin(), stopWords.end(), [&story,&stopWordsCountFile](std::string& sw) {
std::regex re{sw}; // One of the "stop words"
stopWordsCountFile << sw << " --> " << // Write count to output
std::distance(std::sregex_token_iterator(story.begin(), story.end(), re, 1), {}) << "\n";});
// 4. Replace "stop words" in story and write new story into file
std::ostringstream wordsToReplace; // Build a list of all stop words, followed by an option white space
std::copy(stopWords.begin(), stopWords.end(), std::ostream_iterator<std::string>(wordsToReplace, "\\s?|"));
storyCleanedFile << std::regex_replace(story,std::regex(wordsToReplace.str()), "");
}
else {
// In case that any of the files could not be opened.
std::cerr << "\n*** Error: Could not open one of the files\n";
}
return 0;
}
Please try to study and understand this code. This is a very simple solution.
I want to read a file into an int array , but I need to do that one element at a time.
Here's what's in the file :
1000320
0110313
3333000
2033000
2203011
2000010
And here is the code :
std::ifstream fin("file.in");
for (int i=0; i<6; ++i) //rows
{
for (int j=0; j<7; ++j) //columns
{
fin>>_array[i][j];
}
}
If I would print _array[0][0] it will output everything that's on the first line. However I want to split what's in the file into rows and columns .
What's the most elegant way to do this for an INT array ( I don't want to use a char array although it would be much easier . Also , I know that if I put spaces between the numbers in my file the program would read them one at a time but I want them to be like this )
You can try using getchar()
You'll get char but just convert it to int immediately
char temp = getchar(fin);
_array[i][j] = temp - '0';
Unfortunately there's no getint()
in case you want to keep the same structure
#include<fstream>
int main() {
int n;
fstream fin("urfile.txt");
string line;
int _array[6][7];
for (int i = 0; i < 6; ++i) //rows
{
std::getline(read, fin);
for (int j = 0; j < 7; ++j) //columns
{
_array[i][j] = line[j]-'0';
cout << _array[i][j];
}
cout << '\n';
}
fin.close();
}
The following code works fine when reading two .txt files containing two 5X5 array.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <vector>
#include <sstream>
using namespace std;
int main()
{
string myFile, mysecondFile, mystring;
string DIR;
string extension;
int total = 0;
int number_of_lines = 0;
string line;
extension = ".txt";
DIR = "H:\\Year2\\EE273\\EE273\\Week6\\";
cout << "Enter the name of the file: \t";
cin >> myFile;
cout << "Enter the name of the second file: \t";
cin >> mysecondFile;
myFile = DIR + myFile + extension;
mysecondFile = DIR + mysecondFile + extension;
ifstream inFile;
ifstream inFile2;
int i=5;
int j=5;
int i2=5;
int j2=5;
int i3=5;
int j3=5;
int k;
int l;
int Array[5][5];
int Array2[5][5];
int Array3[5][5];
string attempt1,attempt2;
int row = 0;
int col = 0;
int row2 = 0;
int col2 = 0;//i = row
//y = column
inFile.open(myFile.c_str());
if (!inFile) {
cout <<"Error opening file"<<myFile<<endl;
return -1;
}
while (!inFile.eof())
{
getline(inFile, attempt1);
stringstream iss( attempt1 );
string result;
col = 0;
while (getline( iss, result, ','))
{
//cout << result << endl;
Array[row][col] = atoi(result.c_str());
//j = j + 1;
col = col + 1;
}
row = row + 1;
}
inFile.close();
inFile2.open(mysecondFile.c_str());
if (!inFile2) {
cout <<"Error opening file"<<mysecondFile<<endl;
return -1;
}
while (!inFile2.eof())
{
getline(inFile2, attempt2);
stringstream iss( attempt2 );
string result2;
col2 = 0;
while (getline( iss, result2, ','))
{
//cout << result2 << endl;
Array2[row2][col2] = atoi(result2.c_str());
col2 = col2 + 1;
}
row2 = row2 + 1;
}
inFile2.close();
/*for (int i=0;i<5;i++){
for (int j=0; j<5; j++){
cout<<Array[i][j]<<endl;}}
for (int i2=0;i2<5;i2++){
for (int j2=0; j2<5; j2++){
cout<<Array2[i2][j2]<<endl;
}}
Here I am carrying out the multiplication between the two matrices and writing the resulting values to a third matrix.
int Total=0;
i=0;
j2=0;
j=0;
j3=0;
for (i3=0; i3<5; i3++) {
while(j3<5){
while (j<5){
for (i2=0;i2<5;i2++){
Total += Array[i][j]*Array2[i2][j2];
j++;
Array3[i3][j3]=Total;
}}
j=0;
j2++;
j3++;
Total=0;
}
i++;
j=0;
j2=0;
j3=0;
Total=0;
}
My question is: what is the easiest way to modify the code so that it can read two .txt files containing an array of any size and then carry out the multiplication successfully?
EDIT I have to do this using arrays only, I can't use vectors unfortunately.
Am I correct in thinking the new operator is involved?
The "easiest" way would be to do something naive, like reading the file once fully to get the number of rows/cols, then reading the file again to actually store the values in the matrix:
unsigned int rows = 0;
unsigned int cols = 0;
std::string line;
while (std::getline(inFile, line)) {
rows++;
std::stringstream ss(line);
std::string col;
while (std::getline(ss, col, ',')) {
cols++;
}
}
// Now allocate the rows*cols matrix
int** matrix = new int*[rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
// and read your values into the matrix ...
// matrix[m][n] = xxx
It's pretty inefficient to read a file twice; and there are other ways to obtain the size beforehand. For example you could have a convention in your input file to include the matrix width/height before the data:
[infile.txt]
3,3
1,2,3
4,5,6
7,8,9
Now you can read the first line of the file, and you'll know that the rest of this file contains a 3x3 matrix. Allocate your matrix with new (similar to above example), then continue to read the rest of the file into it.
Remember to clean up your dynamically allocated matrices with delete[]. There should be 1 call to delete for every call to new.
for (int i = 0; i < rows; i++) {
delete[] matrix[i];
}
delete[] matrix;
Use std::vector instead of raw arrays. E.g. you can push_back an item on a vector. And more crucially, you can create it with a size known only at run-time, e.g. from information in a file.
The easiest approach requires the file to contain the size of the matrix as its first entries. With that, you can fallback to using C (C++ does not tolerate matrices of dynamic size) and do the following:
Read the dimension of the matrix into variables width and heigh.
Allocate the matrix using
int (*dynamicMatrix)[width] = malloc(height*sizeof(*dynamicMatrix));
Reuse your code to fill the matrix.
If you can't fall back to C, and can't use std::vector<>, the only thing left to you is to use a double pointer:
int**dynamicMatrix = new int*[height];
for(size_t i = width; i--; ) dynamicMatrix[i] = new int[width];
Again, this is easiest if you can define the first two numbers in a file to contain the width and height of the matrix in the file. If you can't code these two numbers into your file, you have to grow your dynamic arrays as you go:
size_t lines = 0, allocatedLines = 8;
int** dynamicMatrix = new int*[allocatedLines];
while(/* can read a line */) {
if(lines == allocatedLines) {
int** temp = new int*[allocatedLines *= 2];
for(size_t i = lines; i--; ) temp[i] = dynamicMatrix[i];
delete[] dynamicMatrix;
dynamicMatrix = temp;
}
//add one line
size_t curLineLength = 0, allocatedLineLength = 8;
dynamicMatrix[lines++] = new int[allocatedLineLength];
//fill the line
...
}
A similar block for reallocating a line would need to go into the loop where you read the elements of a single line. This is tedious; but the only way to get better is to use stuff that you are not allowed to use.
Btw: even the reallocating stuff is easier in C, since it provides the realloc() function:
size_t lines = 0, allocatedLines = 8;
int** dynamicMatrix = malloc(allocatedLines * sizeof(*dynamicMatrix));
while(/* can read a line */) {
if(lines == allocatedLines) {
//realloc takes care of copying the data to a new location (if that is necessary):
allocatedLines *= 2;
dynamicMatrix = realloc(dynamicMatrix, allocatedLines * sizeof(*dynamicMatrix));
}
//add one line
size_t curLineLength = 0, allocatedLineLength = 8;
dynamicMatrix[lines++] = malloc(allocatedLineLength * sizeof(**dynamicMatrix));
//fill the line
...
}
Since there is no equivalent to realloc() to work with new/delete, you are required to either use std::vector<> in C++, or to do the copying yourself as above.
I'm trying to read numbers from a test file and display them in a matrix. In the text file, there is one number per line. The first two lines are the dimensions of the matrix.(3 and 4) I'm having trouble assigning the actual data values of these numbers to the matrix. In this case Values 2 through 14.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
#include "Matrix.h"
int main()
{
CMatrix A(10,10); //set to arbitrary size
int x;
int i = 0;
int number;
int rowsFile;
int columnsFile;
while ( myFile.good()&& myFile.is_open() )
{
myFile>>x;
if (i==0){ //for row dimension
rowsFile = x;
}
if (i==1){ //for column dimension
columnsFile = x;
}
cout<<"Value "<<i<<": "<<x<<endl; //displays the values
if (i>=2){
for (int r = 0; r < rowsFile; r++)
{
for (int c = 0; c < columnsFile; c++)
{
A.Value(r,c) = x;
myFile>>x;
}
}
myFile.close();
}
i=i+1;
}
myFile.close();
CMatrix A(rowsFile, columnsFile);
cout<<endl<< "Rows: "<<A.getNumberOfRows()<<endl;
cout<< "Columns: "<<A.getNumberOfColumns()<<endl;
cout<<endl<<A.ToString();
}
Here is a display of my output.
For some reason my commented out loop doesn't seem to be working.
Any help would be appreciated. Thank you!
While I can't offer you a complete solution due not completely understanding what you're trying to do, I recommend reading the contents of the file line wise and storing them in a vector, as in this example:
std::ifstream ifs("file.txt");
std::string line;
std::vector<std::string> lines;
if (ifs.good()) while (getline(ifs, line)) lines.push_back(line);
else throw std::runtime_error("An error occurred while trying to read from file.");
This makes it easier to work with the data.
I suggest you reorganize this code to place doubles into matrix elements immediately after reading them.
The file io code may not be perfect, but I would separate the reading of the number of rows and columns from the loop that handles the element values.
// do not declare i here
int numRows;
int numCols;
std::fstream inputFile("filename", std::in);
if ! (inputFile >> numRows >> numCols)
{
// Handle error
}
// Check that numRows and numCols are acceptable (positive)
// [not shown]
CMatrix A(numRows, numCols);
if (inputFile)
{
int elementsRead = 0;
for (int i = 0; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
double x;
if (inputFile >> x)
{
A.Value(i,j) = x;
++elementsRead;
} else {
// probably an error from too-short file,
// token could not be converted to double, etc.
// handle appropriately
break;
}
}
}
}
if (elementsRead != numRows * numCols)
{
// handle error
}
// Use matrix A
I am trying to read the unknown contents of a text file into a 2D array and have it come out looking like:
M [0] [0]=2 M [0] [1]=1 M [0] [2]=0
M [1] [0]=0 M [1] [1]=1 M [1] [2]=3
M [2] [0]=8 M [2] [1]=9 M [2] [2]=1
M [3] [0]=3 M [3] [1]=5 M [3] [2]=2
when the text file looks like this:
2
1 0
0 1
3
8 9 1
3 5 2
-2 3 -1
0
The zero at the end shows the end of the file.
My problem is the array can be a max size of 10X10 so there is no way of knowing what the size of the 2D array is and how to get it to look like i have shown above.
Any ideas?
Just use 'fstream'. It ignores new lines and works just like 'iostream'. You just need to keep track of your matrix row and column.
//open "myFileName.txt" with an input file stream
std::ifstream inputFile("myFileName.txt");
while(!inputFile.eof()) //Check for end-of-file character
{
//do this while keeping track of your matrix position
inputFile >> M [curRow] [curColumn]
}
inputFile.close();
And don't forget to include the library:
#include <fstream>
Edit: The >> operator will also attempt to auto-cast the input as whatever type you are using:
double dTemp;
int iTemp;
std::string sTemp;
std::ifstream in("myFile.txt");
in >> dTemp; //input cast as double
in >> iTemp; //input cast as integer
in >> sTemp; //input cast as string
in.close();
Edit: Get the number of elements of the file
int temp, numberOfInputs;
while(!inputFile.eof())
{
inputFile >> temp;
++numberOfInputs;
}
inputFile.seekg(0, std::ios::beg); //Go to beginning of file
Once you have the number of inputs you can use that to figure out the number of rows and colums.
For some dimensions N x M
char c;
int x;
for(int i = 0; i < N; i++)
{
for(int j = 0; j < M; j++)
{
c = fgetc(file);
if(c == ' ') continue;
if(c == EOF) return;
if(c == '-')
{
c = fgetc(file);
x = -1 * ((int)c);
} else {
x = c;
}
if(x == 0)
{
array[i][j] = x;
} else {
return;
}
}
}
But if you're talking about "what's the size of the matrix required to store these" then you're going to need a way to figure out what dimensions you want.
Try:
#include <vector>
#include <fstream>
#include <iostream>
int main()
{
std::ifstream file("plop.dat");
if(!file)
{
std::cerr << "Failed to open File\n";
return 1;
}
// Keep looping until we are done.
while(true)
{
int size;
file >> size;
// You said a size zero indicates termination.
if (size == 0)
{ break;
}
// Create a square 2D vector (Vector inside a Vector)
std::vector<std::vector<int> > matrix(size, std::vector<int>(size, 0));
// Loop over each axis
for(int x = 0;x < size; ++x)
{
for(int y = 0;y < size; ++y)
{
// Read one number for each location.
// The operator >> automatically skips white space
// White Space includes newline and tab. So it should work
// perfectly if the input is OK. But it is hard to detect
// an error in the format of the file.
file >> matrix[x][y];
}
}
}
}
~
So all row of the array have 3 values?
Simply read the values into the array keeping a count of which column you are in and ignore the newlines?
Look at getline
getline and stringstream to read, vector< vector<int> > to store.
Edit: Oh, so the size is always N*N? Then just read using while(cin>>x) { if (cin.good()) ...; } into a vector<int>, check the total size, and split into vector< vector<int> >
Single and multi-dimensional C arrays are just contiguous pieces of memory. The difference is more syntactical in terms of what indexing into the array does: for a 2-dimensional array it just multiplies one dimension by the size of the other dimension before adding the second dimension to find the offset.
So to solve:
read the values into a std::vector (other answers have sugegsted ways to do this)
work out the size (integer square root of myArray.size())
calculate the index as, e.g.:
int idx(int size, int d1, int d2)
{
return (d1*size)+d2;
}
Return the vector element at the index e.g.:
for (int d1 = 0; d1 < size; d1++)
{
for (int d2 = 0; d2 < size; d2++)
std::cout << "M [" << d1 << "] [" << d2 << "]=" << myArray[idx(size, d1, d2)] << " ";
std::cout << std::endl;
}
gives me:
$ g++ arr.cpp && ./a.out
M[0][0]=2 M[0][1]=1 M[0][2]=0
M[1][0]=0 M[1][1]=1 M[1][2]=3
M[2][0]=8 M[2][1]=9 M[2][2]=1