Swap values of x and y - c++

How can I change the values of x and y in this code?
When I try to do it by x=y, y=x; it changes it to the same numbers.
How can I do this?
How can I do this for 3 values like (x y z)?
#include <iostream>
using namespace std;
int main()
{
int x=4;
int y=6;
cout<<x<<y;
return 0;
}
I tried this code before but it isn't working the way I want it.
#include <iostream>
using namespace std;
int main()
{
int x=4;
int y=6;
x=y,y=x;
cout<<x<<y;
return 0;
}

This is because you first set x's value and then copy that value into y. There is a standard library function called std::swap, which should do the job.
You can see an exapmle of it here.
std::swap is defined in the header <algorithm> before C++11 and in <utility> since C++11. So make sure you #include the correct header.
The benefit of using std::swap in C++11 as opposed to having a third temporary variable that you copy the value into, is that std::swap uses std::move and thereby creates no additional copies.
For three numbers you'll have to make your own implementation like this:
#include <iostream>
int main() {
int x{5}, y{3}, z{2};
int temp{std::move(x)};
x = std::move(y);
y = std::move(z);
z = std::move(temp);
std::cout << x << ' ' << y << ' ' << z << '\n';
return 0;
}
Ideone

For 2 variables, you should use std::swap, for more variables, you may use std::tuple:
std::tie(x, y, z) = std::make_tuple(y, z, x);
Demo

There are two options:
Introduce temporary variable:
int temporary = y;
y = x;
x = temporary;
Or use std::swap like this std::swap(x, y); (you might need to import <algorithm> or <utility>)
Now why you are getting this error? Let's analyze what you are doing here step by step:
x = y; Give x value of y. So now x is equal to y
y = x; Give y value of x. But wait, x is now equal to y. So nothing changes.
If you still have trouble understanding what you did wrong I suggest taking a piece of paper and following your own code step by step on paper writing state of program at each step.
And one last thing as advice for the future. Please make you questions clear and properly formatted. For example, it totally don't understand your point with 3 values. Please explain what you mean and probably provide some example and then maybe someone will be able to help you.

try this:
#include <iostream>
using namespace std;
int main()
{
int x=4;
int y=6;
int temp=x;
x=y;
y=temp;
cout<<x<<y;
return 0;
}

Without using a third variable you can do swapping two variables like this,
#include <iostream>
using namespace std;
int main()
{
int x=4;
int y=6;
x = x + y;
y = x - y;
x = x - y;
cout<<"X = "<<x << "\n"
<<"Y = "<<y;
return 0;
}
So the output will be,
X = 6
Y = 4

x=4
y=6
x=y // x=6, y=6
y=x // does nothing
Try using another variable:
#include <iostream>
using namespace std;
int main()
{
int x=4;
int y=6;
int temp=x;
x=y,y=temp;
cout<<x<<y;
return 0;
}

Here is code to swap 2 variables(1 line)
#include <iostream>
using namespace std;
int main()
{
int x = 4;
int y = 6;
cout << x<< y;
swap(x,y);
cout << x << y;
getchar();
return 0;
}
Here is code to swap 3 variables(1 line)
#include <iostream>
#include <tuple>
using namespace std;
int main()
{
int x = 4;
int y = 6;
int z = 8;
cout << x<< y<<z;
tie(x, y, z) = make_tuple(y, z, x);
cout << x << y << z;
getchar();
return 0;
}

Related

Illegal hardware instruction on a c program compiled on Mac

I am getting an illegal hardware instruction error when compiled on mac. Appreciate any pointers.
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int * x;
*x=10;
cout << fun(x);
return 0;
}
Pointers are just pointers. In your code there is no integer that you could assign a value to.
This
int * x;
Declares x to be a pointer to int. It is uninitialized. It does not point anywhere. In the next line:
*x=10;
You are saying: Go to the memory that x points to and assign a 10 to that int. See the problem? There is no int where x points to, because x doesnt point anywhere. Your code has undefined behavior. Output could be anything.
If you want to assign 10 to an int you need an int first. For example:
#include<iostream>
using namespace std;
int * fun(int * x)
{
return x;
}
int main()
{
int y = 0;
int * x = &y;
*x=10;
cout << fun(x);
return 0;
}
This assigns 10 to y. The cout is still printing the value of x, which is the adress of y. It does not print the value of y. Not sure what you actually wanted.
The problem is that in your program the pointer x is not pointing to any int variable. So first you have to make sure that the pointer x points to an int object as shown below.
You can sovle this as shown below:
int i = 0; //create the int object to which x will point
int *x = &i; //make x point to variable i
*x = 10; //dereference the pointer x and assign 10 to the underlying variable i
cout << *fun(x); //this prints 10

Take the sum of two integers and add another integer to the sum continuously

I would like to make a C++ program that takes the sum of two integers and adds another integer to the sum continuously. Please help, I'm a beginner. My code looks like this, except it doesn't update the next sum:
#include <iostream>
using namespace std;
int main() {
int x;
while (cin>>x){
int y=100;
int sum;
sum = x+y;
cout<<sum<<endl;
}
return 0;
}
Your sum variable is declared inside the loop body, so it will be wiped out on each iteration. You need to move that variable outside of the loop, eg:
#include <iostream>
using namespace std;
int main() {
int sum = 100, x;
while (cin >> x){
sum += x;
cout << sum << endl;
}
return 0;
}

X is used uninitialized in this function

Why am i getting this warning?:
warning: 'row1[3]' is used uninitialized in this function [-Wuninitialized]
I've been googling this for some time but but i can't find any answers, probably just because i'm inept at searching answers on Google.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int setfunc(int x);
int main()
{
int row1[3]{0,0,0};
setfunc(row1[3]);
}
int setfunc(int x[])
{
string sub;
int rowset;
stringstream rs;
string snums;
int elementnum = sizeof(x) / sizeof(0);
for(int z = 1; z <= elementnum; z++)
{
int find = snums.find(",");
if(find == -1)break;
else
{
sub = snums.substr(0, snums.find(","));
rs << sub;
rs >> rowset;
snums.erase(0, snums.find(",") +1);
}
x[z] = rowset;
cout << x[z] << endl;
}
return 0;
}
All help appreciated
The behaviour of int row1[3]{0,0,0}; setfunc(row1[3]); is undefined. This is because the indexing runs from 0 to 2, so row1[3] is accessing the array outside its bounds. The compiler is helping you here, although in my opinion, the warning is a little misleading.
sizeof(x) / sizeof(0); is also incorrect. sizeof(0) is the size of an int since 0 is an int type. The normal idiom is sizeof(x) / sizeof(x[0]). But you can't do this either in your case since the function parameter x will have decayed into a pointer. You ought to pass the number of elements into the function explicitly.

search a number in an unsorted array

I have a code that searches for a given entry in an array, and returns the position in the array of that entry, provided one knows the array contain that number. However, a strange thing happens. When I try to test the code with some concrete arrays, the code works well for some entries, and it does not work for others. The code is this:
#include <iostream>
#include <cmath>
using namespace std;
int Find_entry(int data[], int n, int x)
{
int a = (n/2);
int b = n;
int tmp = 0;
while (x != data[a])
{
if (x > data[a])
{
tmp = a;
a = (b+a)/2;
b = b;
}
if (x < data[a])
{
a = tmp;
b = a;
}
}
return a;
}
(in a previous version I was using the floor function to round the numbers contained in a to their integer parts, but I understand this is not necessary.)
I have tested the program for example for the following array in this main:
int main()
{
int n = 6; int x = 12;
int array1[] = {3,12,5,9,7,11};
cout << "The entry " << x << " is found at position "
<< 1+Find_entry(array1, n, x) << endl;
return 0;
}
When I type as in this example x=12, the program gives the correct answer 1. Same thing for x=3, x=11 and x=9. But if I type x=7 or x=5, the program refuses to give an output and I get a message like
"Process terminated with status -1073741510 (0 minute(s), 9 second(s))".
Can anybody explain what's the problem here? How can be the code fixed?? Thank you all for your answers.
You cannot use binary search for unsorted array. Use linear search.
int Find_entry(int data[], int n, int x)
{
int a = 0;
while (a < n && x != data[a]) a++;
return a;
}
Binary search only works on sorted inputs.

How to solve Lee's Algorithm in C++?

I'm trying to solve a C++ problem using Lee's Algorithm (a maze). I have to find a place where two people meet at the exact same time (the shortest), knowing that R and J represent the places where they start and X are the obstacles. This is how rj.in looks :
5 8
XXR XXX
X X X
J X X X
XX
XXX XXXX
And the problem is that when I read it, it always has the same value. What am I doing wrong? This is my code, and this is where the problem appears:
#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
#define ex -1
#define red(X) scanf("%d",&X);
const int MAX=150;
int ro [MAX][MAX],ju [MAX][MAX];
inline int inside(int x,int y,int n,int m)
{
return x>=1 and x<=n and y>=1 and y<=m;
}
queue<pair<int,int> > Qr;
queue<pair<int,int> > Qj;
int dx[]={0,0,-1,1};
int dy[]={1,-1,0,0};
int main()
{ freopen("rj.in","r",stdin);
freopen("rj.out","w",stdout);
int rx_n,ry_n,jx_n,jy_n,n,m,i,j,t;
red(n);
red(m);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
red(t);
printf("%d ",t);
if((char)t=='X') {ro[i][j]=-1; ju[i][j]=-1; }
if((char)t=='R') {ro[i][j]=1; Qr.push(make_pair(i,j));}
if((char)t=='J') {ju[i][j]=1; Qj.push(make_pair(i,j));}
}
I'm using the C functions because they are faster.