Given the following program what will the output be? Please explain, not just gi
ID: 3721610 • Letter: G
Question
Given the following program what will the output be? Please explain, not just give me the answer. I know it is 11 31
#include using
namespace std;
void one(int x, int& y);
void two(int& s, int t);
int main()
{
int u = 1;
int v = 2;
one(u, v);
cout << u << " " << v << endl;
two(u, v);
cout << u << " " << v << endl;
return 0;
}
void one(int x, int& y)
{
int a;
a = x;
x = y;
y = a;
}
void two(int& s, int t)
{ int b;
b = s - t;
s = t + b + 2;
t = 4 * b;
}
Explanation / Answer
ANSWER: I have run your code and it is giving the same output as you mention in this question.and explanation I added in the code as a comment you can check.
CODE:
#include <iostream>
using namespace std;
void one(int x, int& y);
void two(int& s, int t);
int main()
{
int u = 1;
int v = 2;
one(u, v);// Here you are passing 1 and 2 in this function after going int his function you are passing the address of v and in this function swapping is performed so in this funtion v is changed to its address and after this function v contain 1 but u are passing as a value so it contains its original value 1 that's why it is printing 1 1.
cout << u << " " << v << endl;
two(u, v);// Here you are passing u and v value again and in this function you are passing the address of u and changes its value to 3 in the funtion so thats why it is printing 3 1 aftwer this function same as above concept is used here
cout << u << " " << v << endl;
return 0;
}
void one(int x, int& y)
{
int a;
a = x;
x = y;
y = a;
}
void two(int& s, int t)
{ int b;
b = s - t;// here b will be 1-1 =0
s = t + b + 2;// s will be 1+0+2=3 and it is changes its address so it is permanent change.
t = 4 * b;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.