Why I am getting wrong values from accessing 2D array in C? - c

I have this following program which calculates the determinant of an NxN matrix, the program itself works, but when I try to calculate the 2nd order matrix determinant at the end of recursion, accessing the 2d 2x2 array elements gives me wrong values.
I am using recursion to be able to calculate the determinant of higher-order matrices, findDet() is the recursive function, that uses a loop to call itself for each element of the first row in a given matrix and sub-matrices if their order is greater than two.
/******************************************************************************
Program to find the determinant a matrix
*******************************************************************************/
#include <stdio.h>
#define N 3
long int findDet(int arr[][N], size_t order); // To find the determinant
void initNewArr(int newArr[][N-1], int prevArr[][N], size_t order, int exCol); // To create sub matrices
int main()
{
int order = N;
printf("This program is to find determinant of a given matrix.\n\
\rNumber of row and column is going to be equal.\n");
// printf("Enter the order of the matrix: ");
// scanf("%d", &order);
// Read the input matrix from the user
int matrix[order][order];
printf("Enter matrix elements...\n");
for(int i = 0; i < order; i++) {
for(int j = 0; j < order; j++) {
printf("Enter matrix[%d][%d]: ", i+1, j+1);
scanf("%d", &matrix[i][j]);
}
}
// Print the matrix
printf("New Matrix itself...\n");
for(int i = 0; i < order; i++) {
for(int j = 0; j < order; j++) {
printf("%d\t", matrix[i][j]);
}
printf("\n");
}
// Calling findDet() to calculate determinant and store it in "det"
long int det = findDet(matrix, order);
// Print the determinant
printf("\nDeterminant of the matrix = %li", det);
return 0;
}
long int findDet(int arr[][N], size_t order) {
// if order is 2 calculate the determinant of 2nd order matrix
if(order == 2) {
int detS = ((arr[0][0]) * (arr[1][1])) - ((arr[0][1]) * (arr[1][0]));
/*
This following expression shows that accessed values are not correct
for this reason, the calculated determinant of 2nd order matrix is
not correct.
The whole problem is in this block of code
*/
printf("=== arr[0][0] * arr[1][1] - arr[0][1] * arr[1][0] = %d * %d - %d * %d\n", arr[0][0], arr[1][1], arr[0][1], arr[1][0]);
printf("Result of above expression === %d\n", detS);
return detS;
} // if order is higher then continue to break down matrix to 2nd order step by step
long int det = 0;
/*
The following for loop is for multiplying each element of
first row by determinant of sub-matrix,
which in case of below 3x3 matrix:
2 -3 1
2 0 -1 its determinant = 2 * (det of sub-matrix1) - (-3) * (det of sub-matrix2) + 1 * (det of sub-matrix3)
1 4 5
sub-matrices are:
>>> sub-matrix1
0 -1
4 5 --> in the first iteration of the array inside findDet()
while accessing the
arr[0][0] gives value 0
arr[0][1] gives value -1
arr[1][0] gives value 5
arr[1][1] gives value 1
>>> sub-matrix2
2 -1
1 5 --> in the second iteration of the array inside findDet()
while accessing the
arr[0][0] gives value 2
arr[0][1] gives value -1
arr[1][0] gives value 5
arr[1][1] gives value 1
>>> sub-matrix3
2 0
1 4 --> in the third iteration of the array inside findDet()
while accessing the
arr[0][0] gives value 2
arr[0][1] gives value 0
arr[1][0] gives value 4
arr[1][1] gives value 1
But since we get wrong values for sub-matrices the final determinant is not correct
*/
for(int i = 0; i < order; i++) {
// New sub matrix in each iteration
int newArr[order-1][order-1];
initNewArr(newArr, arr, order, i);
// Print the sub matrix
printf("\nNewly Created Sub Matrix itself...\n");
for(int i = 0; i < order-1; i++) {
for(int j = 0; j < order-1; j++) {
printf("%d\t", newArr[i][j]);
}
printf("\n");
}
// Calculate Determinant
if(i % 2 == 0) { // if i is 0 or even which then becomes odd-th element of matrix add result to det
det += (arr[0][i] * findDet(newArr, order-1));
} else { // otherwise subtract the result from the det
det -= (arr[0][i] * findDet(newArr, order-1));
}
}
return det;
} // ================== findDet()
void initNewArr(int newArr[][N-1], int prevArr[][N], size_t order, int exCol) {
for(int i = 0; i < order; i++) {
for(int j = 0; j < order; j++) {
if(i != 0 && j != exCol) { // When element is not in first row and exCol(excluded column) assign it to sub matrix
newArr[i-1][j > exCol ? j-1 : j] = prevArr[i][j]; // When column is greater than exCol subtract 1 from it
}
}
}
}
The recursion works perfectly and the problem is in the expression denoted above.
edit
for example if I input
2 -3 1
2 0 -1
1 4 5
while accessing the arr[0][0], arr[0][1], arr[1][0] and arr[1][1] in following sub-matrices
0 -1
4 5 --> in the first iteration of the array inside findDet()
2 -1
1 5 --> in the second iteration of the array inside findDet()
2 0
1 4 --> in the third iteration of the array inside findDet()
don't give me all the original values, they give some random values and some values that exist in the matrix.
you can check code comments for more details, I know this question is long and a bit confusing but I wish some of you can help me?
Can you please help me find the problem?
Thanks

Related

how can I print the final matrix correctly?

Problem Statement
A matrix is a 2D array of numbers arranged in rows and columns. We give you a Matrix of N rows and M columns.
Now your task is to do this operation on this matrix:
If the value matches with the current row and column number then add 3 with the value.
If the value matches with only the current row number then add 2 with the value.
If the value matches with only the current column number then add 1 with the value.
Input Format
The first line contains N is the number of rows in this matrix and M is the number of columns in this matrix
The second line contains a 2D array Arr[i][j].
Constraints
1 <= N, M <= 10
0 <= Arr[i][j] <= 100
Output Format
Print the matrix after the operation is done.
Sample Input 0
3 3
1 1 1
1 1 1
1 1 1
Sample Output 0
4 3 3
2 1 1
2 1 1
#include <stdio.h> 
int main(){
//here taking the row and column from the users
int row;
int column, temp;
printf("enter row and column\n");
scanf("%d%d", &row, &column);
int arr[row][column];
//here taking the matrix input through the users
for(int i = 0; i < row; i++){
for(int j = 0; j < column; j++){
scanf("%d", &arr[i][j]);
}
for (int i=0; i<row; i++){
for(int j=0; j<column; j++ ){
if (arr[i][j] == arr[i+1] && arr[i][j]== arr[j+1]){
temp= arr[i][j]+3;
printf("%d", temp);
}
else if (arr[i][j] == arr[i+1]){
temp= arr[i][j]+ 2;
printf("%d", temp);
}
else if (arr[i][j]== arr[j+1]){
temp= arr[i][j]+ 1;
printf("%d", temp);
}
else{
temp= arr[i][j];
printf("%d", temp);
}
}
}
}
return 0;
}
After I run the code, this doesn't work.
At least this issue:
if (arr[i][j] == arr[i+1] && arr[i][j]== arr[j+1]){ is undefined behavior (UB) as code attempts to access outside int arr[row][column]; with arr[i+1] and arr[j+1].
arr[i][j] == arr[i+1] is not sensible as it attempts to compare an int with a pointer.
In c, there are two types of memories. One of them is run-time memory, where your program dynamically allocates memory based on actions done in the program execution time.
In your answer, you are setting your matrix size based on the numbers inputed by the user, which is dynamic memory.
A static array(what you are using) is not dynamic and it is the reason that you can't add more elements and change the size of it.
https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/amp/

Rearranging rows in dynamically allocated 2D array in C

I'm currently working on a program in C where I input matrix dimensions and elements of a matrix, which is represented in memory as dynamic 2D array. Program later finds maximum of each row. Then it finds minimal maximum out of maximums of all rows.
For example,
if we have 3x3 matrix:
1 2 3
7 8 9
4 5 6
maximums are 3, 9, 6 and minimal maximum is 3. If minimal maximum is positive, program should proceed with rearranging order of rows so they follow ascending order of maximums, so the final output should be:
1 2 3
4 5 6
7 8 9
I made a dynamic array which contains values of maximums followed by row in which they were found, for example: 3 0 6 1 9 2. But I have no idea what should I do next. It crossed my mind if I somehow figure out a way to use this array with indices I made that I would be in problem if I have same maximum values in different rows, for example if matrix was:
1 2 3
4 5 6
7 8 9
1 1 6
my array would be 3 0 6 1 9 2 6 3. I would then need additional array for positions and it becomes like an inception. Maybe I could use some flag to see if I've already encountered the same number, but I generally, like algorithmically, don't know what to do. It crossed my mind to make an array and transfer values to it, but it would waste additional space... If I found a way to find order in which I would like to print rows, would I need an adress function different than one I already have? (which is, in double for loop, for current element - *(matrix+i * numOfCols+currentCol) ) I would appreciate if somebody told me am I thinking correctly about problem solution and give me some advice about this problem. Thanks in advance!
I don't know if I have understood it correctly, but what you want to do is to rearrange the matrix, arranging the rows by the greatest maximum to the least...
First, I don't think you need the dynamic array, because the maximums are already ordered, and their position on the array is enough to describe the row in which they are.
To order from maximum to minimum, I would make a loop which saved the position of the maximum and then, use it to store the correspondent row in the input matrix into the output matrix. Then, change the value of that maximum to 0 (if you include 0 in positives, then change to -1), and repeat the process until all rows have been passed to the output matrix. Here is a sketch of what it would look like:
for(k = 0; k < n_rows; ++k)
for(i = 0; i < n_rows; ++i)
if (max[i] > current_max)
current_max = max[i];
max_row = i;
for(c = 0; c < n_columns; ++c)
output_matrix[row][c] = inputmatrix[max_row][c];
max[max_row] = 0;
Array is not dynamic because we can not change the size of array, so in this case you can use double pointer, for example, int **matrix to store the value of 2D array.
The function for searching the max value of each row and the row index of each max value:
int * max_of_row(int n, int m, int **mat) {
// allocate for n row and the row index of max value
int *matrix = malloc (sizeof(int) * n*2);
for(int i = 0; i < 2*n; i++) {
matrix[i] = 0;
}
int k = 0;
for(int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(matrix[k] < mat[i][j]) {
matrix[k] = mat[i][j];
}
}
matrix[k+1] = i;
k += 2;
}
return matrix;
}
The main function for test:
int main(int argc, char const *argv[])
{
// allocate for 4 rows
int **matrix = malloc (sizeof (int) * 4);
for (int i = 0; i < 4; i++) {
// allocate for 3 cols
matrix[i] = malloc(sizeof(int) * 3);
for(int j = 0; j < 3; j++){
matrix[i][j] = i+j;
}
}
int * mat = max_of_row(4, 3,matrix);
printf("matrix:\n");
for (int i = 0; i < 4; i++) {
for(int j = 0; j < 3; j++){
printf("%d ",matrix[i][j]);
}
printf("\n");
}
printf("max of row and positon\n");
for (int i = 0; i < 8; i++) {
printf("%d ", mat[i]);
}
printf("\nmax of row\n");
for (int i = 0; i < 8; i += 2) {
printf("%d ", mat[i]);
}
printf("\n");
return 0;
}
Output:
matrix:
0 1 2
1 2 3
2 3 4
3 4 5
max of row and positon
2 0 3 1 4 2 5 3
max of row
2 3 4 5

How to Pass multiple arrays from a function into main?

Im not used to using pointers or coding in C. I've created a void function in which I defined a couple arrays and populated them using my Input parameters. Now I need to use these arrays in my main but unsure on how to call them. Following is my function code :
void showCDF(int Integer_Array[], int length){ //Calculates the CDF and stores it in "y_values"
int i = 1; // i initialized at 1
int y_axis[20];
int size_of_x = Integer_Array[length-1]- Integer_Array[0]+1; // size of x is the difference between the first and
int x_axis[size_of_x]; // last element of input array.
x_axis[0] = Integer_Array[0]; // first element of x is the first element of input array
//printf("%d ", x_axis[0]); // print out the first element
while (x_axis[i-1]<Integer_Array[length-1]){ // while previous element of x < last element of Input
x_axis[i]= x_axis[i-1] + 1; // adding the previous value of x to 1 store as this value
//printf("%d ", x_axis[i]); // print out all consecutive elements of x
i +=1;
}
printf("\n");
for (i=0;i<21;i++){
y_axis[i] = 5*i;
//printf("%d \n",y_axis[i]);
}
int y_values[size_of_x + 1]; // size of y is dependant on the size of x
for (int j=0; j < size_of_x +1 ; j++){
float n = 0; // Count to show total, initialized at 0
int i= 0;
while (x_axis[j] >= Integer_Array[i] && i<length){ // While x at j is greater than or equal to values of
n ++; // Integer_array at i, AND i is less than length.
i ++; // Then increase the count and i
} // else:
y_values[j]=(n/length)*100; // Then corresponding y at j= % of n / length (or the cdf)
//printf( "%d ", y_values[j]); // print out the cdf
}
}
In my main Im calling my function and variables y_axis, y_value, x_axis like this:
int y_axis[20];
showCDF(integerArray, NUMBER_ENTRIES);
for (i=0;i<21;i++){
printf("%d \n", y_axis[i]);
}
But this just gives me a gibberish number like:
0
0
0
0
0
0
0
0
0
0
0
0
1
0
4199677
0
0
0
0
0
825307441
Any help would be appreciated!

Reordering the rows in a matrix in a specific order

I am successfully storing the calculated subsets in a 2-D array matrix in C language.Now I want to print the subsets in an order desired.
For eg.
2-D array matrix is
10 7 3 2 1
10 7 5 1
7 6 5 3 2
10 6 5 2
10 7 6
Desired Output
10 7 6
10 7 5 1
10 7 3 2 1
10 6 5 2
7 6 5 3 2
How quick sort can be applied to sort/order these rows?
As #chqrlie noted, this can be easily solved with qsort.
Depending on the way the matrix is declared (is it an array of pointers to arrays of ints? do all arrays have the same length? is it a global array of fixed size?) the code will have to do slightly different things.
So, assuming the array is a global variable and all rows have same length (padded with 0s):
MWE:
#include <stdio.h>
#include <stdlib.h>
/*
Compare 2 integers
returns:
-1 if *i1 < *i2
+1 if *i1 > *i2
0 if *i1 == *i2
*/
int intcmp(const int *i1, const int *i2)
{
return (*i2 < *i1) - (*i1 < *i2);
}
#define ROWS 5
#define COLS 5
/*
Assumes rows already sorted in descending order
NOTE: qsort calls the comparison function with pointers to elements
so this function has to be tweaked in case the matrix is an array of
pointers. In that case the function's declaration would be:
int rowcmp(int **pr1, int **pr2)
{
const int *r1 = *pr1;
const int *r2 = *pr2;
// the rest is the same
}
*/
int rowcmp(const int *r1, const int *r2)
{
int i = 0, cmp;
do {
cmp = intcmp(&r1[i], &r2[i]);
i++;
} while (i < COLS && cmp == 0);
return -cmp; /* return -cmp to sort in descending order */
}
int data[5][5] = {
{10,7,3,2,1},
{10,7,5,1,0},
{ 7,6,5,3,2},
{10,6,5,2,0},
{10,7,6,0,0}
};
void printmatrix()
{
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%d ", data[i][j]); /* leaves a trailing space in each row */
}
printf("\n");
}
}
int main()
{
printmatrix();
qsort(data, 5, sizeof(data[0]), (int (*)(const void *, const void *))rowcmp);
printf("\n");
printmatrix();
return 0;
}
For the most flexible solution, I would define
struct row {
size_t len;
int *elems;
};
struct matrix {
struct row *rows;
size_t nrows;
};
and change the code accordingly.
NOTE: code not thoroughly tested, use with caution ;)
First of all, are you sure that the 1 on row 3,col 5 should be there and not on the last line?
Anyway, an efficient way to achieve what you want is:
compute the frequency array
declare a new matrix
go from the highest element (10 in your case) from frequency array and put in your matrix using your desired format.
It is time-efficient because you don't use any sorting algorithm, thus you don't waste time there.
It is NOT space-efficient because you use 2 matrices and 1 array, instead of only 1 matrix as suggested in other posts, but this should not be a problem, unless you use matrices of millions of rows and columns
C code for frequency array:
int freq[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
for(int i=0; i<NO_ROWS; i++) {
for(int j=0; j<NO_COLS; j++) {
if(MATRIX[i][j]!=null && MATRIX[i][j]>0 && MATRIX[i][j]<11) {
freq[MATRIX[i][j]]++;
}
}
}
C code for computing the new matrix dimensions
(assuming you want to keep the number of rows)
OUTPUT_MATRIX[100][100] /*I declared it statically, but I would advise to make it dinamically */
/* first, compute the number columns.
To do so, we need the number of elements
(we get them by simply summing up frequency array's elements) */
int s=0;
for(int i=0; i<11; i++) {
s+=frequency[i];
}
int addOne = 0 /* boolean value to check if we will have to add one extra column for safety */
if(s % NO_ROWS) {
addOne = 1; /* division is not even, so we will have to add extra column */
}
NO_COLS = s/NO_ROWS + addOne;
Now, final part, assigning the values from frequency array to the OUTPUT_MATRIX
int k=0;
int currentNumber = 10; /* assigning starts from 10 */
for(int i=0; i<NO_ROWS; i++) {
for(int j=0; j<NO_COLS; j++) {
if(currentNumber>0) {
if(frequency[currentNumber]==0 || k>=frequency[currentNumber]) {
currentNumber--;
k=0;
}
OUTPUT_MATRIX[i][j] = frequency[currentNumber];
k++;
} else {/*here, you can assign the rest of the value with whatever you want
I will just put 0's */
OUTPUTMATRIX[i][j] = 0;
}
}
}
Hope this helps!
This is what I do in C++ to reorder a matrix:
// b is the matrix and p is an array of integer containing the desired order of rows
for(i=0; i<n; i++){
if( p[i]==i )
continue;
b[i].swap(b[p[i]]);
j = p[i]; // New row i position
// Update row i position to new one
for(int k=i+1; k<n; k++){
if( p[k] == i )
p[k] = j;
}
printRow( b[i] );
}
You need to define an array of pointers of the data type you use and then you can reorder your matrix.
for example your matrix is: arr[5][10], and you want to print line 4 before line 3:
int *[5] arr2;
arr2[0] = &arr[0][0];
arr2[1] = &arr[1][0];
arr2[2] = &arr[2][0];
arr2[3] = &arr[4][0];
arr2[4] = &arr[3][0];
in regard to how will the ordering algorithm work, i would suggest placing a header in the start of each array in the matrix which will tell you how many elements it has(basically the first element of each array can be a counter of the total elements) afterwards you can order the strings by comparing the header, and if it is equal comparing the first element and so on. this can be done in a loop that iterates as many times as there are elements in the array, when the elements are not equal, break out of the loop.
hope this helps.

Program to multiply matrix

Trying to make 3 x 3 matrix multiplier but it gives out wrong output. I don't know what I am doing wrong. Two problems that I am facing are:
(1) Some variables store wrong input. For example a[1][1] shows 7 although I entered 1
(2) The matrix multiplication is wrong
#include <stdio.h>
#include <conio.h>
void matrix_format(int m[2][2])
{
int i,j;
printf("\n\n");
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
if(j==0)
printf("[ %d |",m[i][j]);
else if(j==1)
printf(" %d |",m[i][j]);
else if(j==2)
printf(" %d ] \n",m[i][j]);
}
}
}
int main(void)
{
void matrix_format(int [2][2]);
int a[2][2], b[2][2], r[2][2],m,i,j;
clrscr();
for(m=1;m<=2;m++)
{
if(m==1)
{
printf("Enter values for the matrix A \n");
}
else
{
printf("\n\nEnter values for the matrix B \n");
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
if(m==1)
{
printf("A[%d][%d] : ",i+1,j+1);
scanf("%d",&a[i][j]);
}
else if(m==2)
{
printf("B[%d][%d] : ",i+1,j+1);
scanf("%d",&b[i][j]);
}
}
}
}
printf("\n Matrix A : \n");
matrix_format(a);
printf("\n Matrix B : \n");
matrix_format(b);
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
r[i][j]= a[i][j] * b[j][i];
}
}
printf("\n Matrix Multiplication Result : \n");
matrix_format(r);
getch();
return 0;
}
output:
Please guide me.
The first problem that jumps out is that all your arrays are 2x2, while they should be 3x3:
m[2][2]
should read
m[3][3]
and so on. The number in brackets is the size of the array, not the index of the last element.
This will explain some of the weirdness, in particular why some elements get mysteriously overwritten.
As to the actual matrix multiplication, your algorithm isn't quite right (assuming what you're trying to implement is the standard linear algebra matrix product). Think about what steps are involved in multiplying two matrices, and what your code is actually doing. Since this is homework, I'll only give you a hint:
Matrix product involves summations of element products.
There are two major problems:
First, a 3*3 matrix is represented by int matrix[3][3] not int matrix[2][2]. The reason you see strange results is that you are writing over array boundaries, effectively writing over the other matrix because their memory locations are adjacent.
Note: An array such as int a[10] can only be indexed from 0 to 9.
Another problem is your multiplication. From math, we know that if we have:
C = A x B
Then we have:
C[i][j] = sum(A[i][k]*A[k][j]) over k
That is in your case:
C[i][j] = A[i][0]*A[0][j]+A[i][1]*A[1][j]+A[i][2]*A[2][j]
So you have to have:
for over i
for over j
C[i][j] = 0
for over k
C[i][j] += A[i][k]*B[k][j]
I have written a simple matrix multiplication program without using pointers. Hopefully this would work for you. I can see that you know how to use functions, so try using them more often. Also your multiplication logic was wrong. Read up on that and then see the code. (If you want to do the matrix multiplication for let's say a 5 x 5 matrix, then you should just change #define SIZE 3 to #define SIZE 5).
#include <stdio.h>
#include <stdlib.h>
#define SIZE 3
void CreateMatrix(char name, int m[SIZE][SIZE]) {
int row, col;
printf("Enter values for the matrix %c:\n", name);
for(row = 0; row < SIZE; row++) {
for(col = 0; col < SIZE; col++) {
printf("%c[%d][%d] : ", name, row + 1, col + 1);
scanf("%d", &m[row][col]);
}
}
printf("\n");
}
void PrintMatrix(char name, int m[SIZE][SIZE]) {
int row, col;
printf("Matrix %c:\n", name);
for (row = 0; row < SIZE; row++) {
printf("[ ");
for (col = 0; col < SIZE; col++) {
printf("%d ", m[row][col]);
}
printf("]\n");
}
printf("\n");
}
void MatrixMultiply(int a[SIZE][SIZE], int b[SIZE][SIZE], int mul[SIZE][SIZE]) {
int row, col, k;
for (row = 0; row < SIZE; row++) {
for (col = 0; col < SIZE; col++) {
mul[row][col] = 0;
for (k = 0; k < SIZE; k++) {
mul[row][col] += a[row][k] * b[k][col];
}
}
}
}
int main() {
int a[SIZE][SIZE];
int b[SIZE][SIZE];
int mul[SIZE][SIZE];
// Create Matrices
CreateMatrix('A', a);
CreateMatrix('B', b);
// Matrix Multiplication
MatrixMultiply(a, b, mul);
// Print Matrices
PrintMatrix('A', a);
PrintMatrix('B', b);
PrintMatrix('M', mul);
}
The output:
Enter values for the matrix A:
A[1][1] : 1
A[1][2] : 2
A[1][3] : 3
A[2][1] : 4
A[2][2] : 5
A[2][3] : 6
A[3][1] : 7
A[3][2] : 8
A[3][3] : 9
Enter values for the matrix B:
B[1][1] : 1
B[1][2] : 2
B[1][3] : 3
B[2][1] : 4
B[2][2] : 5
B[2][3] : 6
B[3][1] : 7
B[3][2] : 8
B[3][3] : 9
Matrix A:
[ 1 2 3 ]
[ 4 5 6 ]
[ 7 8 9 ]
Matrix B:
[ 1 2 3 ]
[ 4 5 6 ]
[ 7 8 9 ]
Matrix M:
[ 30 36 42 ]
[ 66 81 96 ]
[ 102 126 150 ]
First, see #aix' answer regarding the array sizes. Then, the reason the multiplication doesn't work is that you are using the wrong formula. The element at i,j in the result matrix is not simply the product of i,j and j,i from the two matrices being multiplied - instead, every element in row i from the left matrix must be multiplied by the corresponding element from column j from the right matrix, and all the products must be added together. See this illustration in the Wikipedia article.
you have define array of 2*2 i.e. it has index of 0,1.but in your FOR loop you are trying to accept 3 i.e.{0,1,2 }elements in one row. so remove = sign from all FOR loops. or just change the declaration of your Array to [3][3].Also then apply right formula for Matrix multiplication i.e r[0][0]=(a[0][0]*b[0][0])+(a[0][1]*b[1][0])+(a[0][2]*b[2][0]). for first cell so on for other cells,in your case for 3*3 matrix.

Resources