C++ help (10 points)?
Clarify why the next C++ function does not behave appropriately and right it.
void swap(int the, int b)
int temp;
temp = the;
b = the;
the = temp;
Virtually any help treasured for uncomplicated 10 points
In ones program,
Why don’t we suppose, the = A FEW, b=7
after that
temp=a; => temp=5;
b=a; => b=5;
a=b => a=5;
Last but not least a=5 as well as b=5, Therefore swapping is just not being done
Alternatively do this
void swap(int the, int b)
int tmp;
tmp=a;
a=b;
b=tmp;
Here tmp = the = FIVE,
a=b => a=7;
b=tmp => b = A FEW;
Therefore now, a=7, b=5, Replacing complete
Thank you, Hope the idea helps
two problems
The swap operate uses contact by cost.i.electronic.the value from the variables your and b are provided for the function.
The values associated with and b are not changed when return.
It is advisable to call by reference or send sometimes shocking pointers to the function
void swap(int &a, int &b)
or
void swap(int *a, int *b)
void swap(int the, int b)
int temp;
temp = the; // support the value involving a
the = b; // place the value involving b around a
b= temp; // place the old value of a into b
You include assigned b first as an alternative to assigning a.The idea is similar to this:First, save you value in a temporary varying (you did this correctly).
Then assign innovative value compared to that saved shifting.In a person’s case, a = b requires come but by publishing “b = a” 1st, you have got destroyed internet stored with b with no first preserving it.
Finally, you assign the next variable internet stored throughout temporary.This is a complete reword:
void swap(int the, int b)
int temp;
temp = the;
the = b; // A PERSON MADE SOME SORT OF MISTAKE HERE
b = temp; // AS WELL AS HERE.RELATING TO JUST “SWEPT” THEM BACK TO RIGHT ORDER.
Change temp = the; to temp = b;
The value you need to save throughout temp may be the one you’re on the verge of clobber inside very next statement.
In addition, make the arguments recommendations:
void swap(int& the, int& b)
…in order that those updates could happen to the actual caller’s aspects, and not merely in your local copy on the arguments for the stack.
It does not swap your numbers.It saves similar value of a.The valuation of b is definitely lost.
At this point it’s correct
void swap(int the, int b)
int temp;
temp = the;
the = b;
the = temp;
The attitudes a and b are on the stack, so whenever you come from the function they is definately swapped.To exchange them you might need to pass your reference.
void swap(int the, int b)
int atemp;
atemp = the;
the = b;
b = atemp;
Does that work
void swap(int & the, int & b)
int temp = the;
the = b;
b = temp;
Leave a Reply
You must be logged in to post a comment.