# Replacing elements in a matrix in C

Darya Wiśniewski

I need to check if an element on the main diagonal of a matrix is ​​even and divisible by the sum of its indices. I remember such elements in 1D arrays:

``````for (i=0; i<n; ++i)
for (j=0; j<m; ++j)
{
if ((i == j) && ((arr[i][j] % 2) == 0))
{
arr2[count] = arr[i][j];
++count;
break;
}
}
``````

Then, replace the elements satisfying the condition with the sum of their indices and set a special condition for  due to division by 0:

``````    count = 0;
for (i=0; i<n; ++i)
for (j=0; j<m; ++j)
{
if ((i+j != 0) && (arr[i][j] == arr2[count]) && ((arr[i][j] % (i+j)) == 0))
{
arr[i][j] = i+j;
++count;
}
else if (((i+j) == 0) && (arr[i][j] == arr2[count])) arr[i][j] = 0;
}
``````

The trouble is that when the first element is even, it's the only replacement number, and that condition doesn't work for other elements: Enthusiastic encoder

# question:

`arr2`Not populated correctly. Once you fill an element into it, you break out of the loop. Note the usage `break`in that loop . Also, you're not updating the value in the `count`else-if condition , which would cause the loop to search the entire loop in vain .`arr2`

# untie:

1. Delete this `break`statement.

2. to `++count`the else-if condition.

bonus:

You wrote ugly code. You are using an extra array which increases the space complexity of the code and with too many loops it also increases the time complexity. You'll understand these things later as you progress, but for now, I'll give you a better solution:

``````// Deal with the (0, 0) case outside the loop
// And avoid an extra else-if inside the loop
if (arr % 2 == 0)
arr = 0;

// There are n diagonal elements in a matrix of order n
// Row and column indexes of a diagonal element are equal
// So you can eliminate the use of j and just rely on i
for (i = 1; i < n; ++i)
// Check if the diagonal element is even and divisible by the sum of the indices
if (arr[i][i] % 2 == 0 && arr[i][i] % (i + i) == 0)
// Replace the element if the condition is satisfied
arr[i][i] = i + i;
``````

As you can see, this method doesn't require any extra space and runs in very good linear time. You can further optimize it by checking if the number is odd by bitwise AND `!(i & 1)`, and can use the bitwise left shift operator to quickly change `i + i`it to odd .`2 * i``(i << 1)`

By the way, why `arr`replace? Division by 0 is undefined .