So I'm trying to swap two numbers without using a third variable. I pass the two numbers I'm trying to swap by reference. When the same number is to be swapped (like 1 is to be swapped with 1), I get an output of zero. I know how to fix this, but I'm unable to understand as to why I keep getting 0 when a and b are the same.
Can anyone explain why I'm getting zero instead of the swapped numbers?
void swap(int *a,int *b)
{
//if(a==b)
// return;
*a=*a+*b;
*b=*a-*b;
*a=*a-*b;
}
int main()
{
int n=3,x=0,y=0;
int a[n][n];
for(int i=0;i<n;i++)
swap(&a[x][i],&a[i][y]);
return 0;
}
It seems you are trying to swap elements of the first row with elements of the first column.
For starters variable length arrays is not a standard C++ feature. Though some compilers have their own language extensions you should avoid their using.
Also the swap function can have undefined behavior because when there is an overflow of a signed integer then the result is undefined. It is better to use the standard C++ function std::swap
.
And in your program you are using an uninitialized array.
Here is a demonstrative program that shows how you could write the code
#include <iostream>
#include <utility>
int main()
{
const size_t N = 3;
int a[N][N];
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
a[i][j] = i * N + j;
}
}
for ( const auto &row : a )
{
for ( const auto &item : row )
{
std::cout << item << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
for ( size_t i = 0; i < N; i++ )
{
std::swap( a[0][i], a[i][0] );
}
for ( const auto &row : a )
{
for ( const auto &item : row )
{
std::cout << item << ' ';
}
std::cout << '\n';
}
std::cout << '\n';
return 0;
}
Its output is
0 1 2
3 4 5
6 7 8
0 3 6
1 4 5
2 7 8
If you want to write your own swap function then write it like
void swap( int *a, int *b )
{
int tmp = *a;
*a = *b;
*b = tmp;
}
and use it in the program like
::swap( &a[0][i], &a[i][0] );