-1

If the value of M is 3, and if value at mat[1][1] is 5, then after interchanging mat[1][1] with mat[1][1] it should be still 5, but instead it is showing 0. But when M is an even number, the code works perfect.

#include<iostream>
#define M 3
void swap( int &a, int &b )
{
        a=a+b;
        b=a-b;
        a=a-b;
}

using namespace std;
int main()
{
    int mat[M][M];
    cout<<"Enter "<<M<<"x"<<M<<" matrix"<<endl;
    for( int i=0; i<M; i++ )
        for( int j=0; j<M; j++ )
            cin>>mat[i][j];


    cout<<endl<<"The real matrix"<<endl;
    for( int i=0; i<M; i++ )
        {
            for( int j=0; j<M; j++ )
            {
                cout<<mat[i][j]<<"\t";
            }
            cout<<endl;
        }


    for( int i=0; i<M; i++ )
    {
        swap( mat[i][i], mat[i][M-i-1] );
    }


    cout<<endl<<"The matrix after diagonal interchange "<<endl;
    for( int i=0; i<M; i++ )
        {
            for( int j=0; j<M; j++ )
            {
                cout<<mat[i][j]<<"\t";
            }
            cout<<endl;
        }

    return 0;
}
Zamir Manihar
  • 121
  • 12

2 Answers2

1

The reason behind this is that you are passing values by reference in swap() function.

Assume that M[1][1] = 5.

When you pass M[1][1] to swap(), they are not copied to a and b. Instead, a and b become the alias for M[1][1].

Let's try to understand what is happening step by step:

a=a+b; // equivalent to M[1][1] = M[1][1] + M[1][1];

When you do this, after the operation, M[1][1] becomes 10. Because a & b are alias to M[1][1], a and b also become 10.

b=a-b; // equivalent to M[1][1] = M[1][1] - M[1][1];

When you do this, M[1][1] becomes 0. Because a & b are alias to M[1][1], a and b also become 0.

a=a-b; // equivalent to M[1][1] = M[1][1] - M[1][1];

When you do this, M[1][1] becomes 0. Because a & b are alias to M[1][1], a and b also become 0.

Edit:

As @SidS suggested, you may use library function std::swap(). If you want to correct your code, just change your swap() with this:

void swap( int &a, int &b )
{
        int tmp = a;
        a = b;
        b = tmp;
}
Kunal Puri
  • 3,419
  • 1
  • 10
  • 22
1

The problem is that you are passing the same value, mat[1][1] for both parameters of your swap() function. Your swap() function does not handle this case correctly, since any change to a is also applied to b and vice versa.

Instead, use std::swap() :

#include <utility>

...
std::swap(mat[i][i], mat[i][M-i-1]);

Or, if you insist on rolling your own, use a temporary variable:

void swap(int &a, int &b)
{
    auto c = a;
    a = b;
    b = c;
}
Sid S
  • 6,037
  • 2
  • 18
  • 24