#include<stdlib.h>
#include<stdio.h>
int main() {
FILE* file = fopen ("fourth.txt", "r");
int i = 0;
int rows=0;
int rows2=0;
int columns=0;
int counter=0;
int length=0;
int multiply=0;
fscanf (file, "%d", &i);
rows=i;
printf("the rows are %d\n", i);
int matrix[rows][rows];
length=rows*rows;
if (rows<=0) {
printf("error, this file cannot be processed");
return 0;
}
do
{
if (fscanf(file, "%d", &i)==1) {
if (counter<length) {
matrix[rows2][columns]=i;
counter++;
columns++;
if (columns==rows) {
rows2++;
columns=0;
}
}
multiply=i;
}
} while (!feof(file));
fclose (file);
for ( int c = 0; c < rows; c++ ) {
for ( int j = 0; j < rows; j++ ) {
printf("matrix[%d][%d] = %d\n", c,j, matrix[c][j] );
}
}
printf("the multiply is %d", multiply);
I am trying to create a matrix exponential (matrix multiplication in another words). However before I perform the actual mathematical process, I have to read numbers as input from a txt file and store them in a 2d array. Above is what I have from the code so far, however, I am struggling to actually input the numbers into the array because when I was testing my 2d array out at the very end, I was getting odd results.
for example: 1. Inputs:
3
123
456
789
2
The 3 represents the number of rows, which is the same as the number of columns for this particular 2d array because the matrix is square, meaning all rows and columns are the same.
The 2 represents the exponent, which is the number of times I have to multiply the original matrix by itself.
However my output is
matrix[0][0] = 123
matrix[0][1] = 456,
matrix[0][2] = 789
matrix[1][0] = 2
matrix[1][1] = 4214800
matrix[1][2] = 0
matrix[2][0] = 3
matrix[2][1] = 0
matrix[2][2] = 0
Expected output has to be:
123
456
789
in a 2d array
Is there a reason why?
Also how would I modify the code so no matter what the input is in the txt file regarding different rows and columns, I could still format the proper 2d array. Thanks