Why is it not work? | Sololearn: Learn to code for FREE!

+2

Why is it not work?

#include <iostream> using namespace std; void swap(int x,int &y) int temp; temp=x; x=y; y=temp; int main() { int a=100; int b=200; cout <<"before swap , value of a "<<a<<endl; swap(a,b); cout <<"after swap , value of a "<<a<<endl; cout <<"after swap , value of b "<<b<<endl; return 0; }

5/17/2022 12:07:21 PM

Sangeetha Santhiralingam

12 Answers

New Answer

+3

Yes by my smallmistake

+3

#include <iostream> using namespace std; void wap(int x,int &y) {int temp; temp=x; x=y; y=temp; } int main() { int a=100; int b=200; cout <<"before swap , value of a "<<a<<endl; wap(a,b); cout <<"after swap , value of a "<<a<<endl; cout <<"after swap , value of b "<<b<<endl; return 0; } function name is swap in that code now see function name is wap

+2

Close the swap function.. edit: Sangeetha Santhiralingam oh. you don't have opening brace also... void swap( int x, int &y) { //add it //function body.. } //add this int main() { .. }

+2

Yes Jayakrishna🇮🇳

+1

+1

why is there a need to define swap? "The function std::swap() is a built-in function in the C++ Standard Template Library (STL) which swaps the value of two variables." you can use swap without having to define it yourself.😁 #include <iostream> using namespace std; int main() { int a = 5; int b = 50; cout << "Before swap:\n"; cout << "a = " << a << endl; cout << "b = " << b << endl; swap(a, b); cout << "After swap:\n"; cout << "a = " << a << endl; cout << "b = " << b << endl; return 0; }

+1

Pass both <x> and <y> by reference void swap( int& x, int& y )

+1

What is your expected outcome by your code? Your code only swaps y value with x. x remains same so x, y have same values. edit: code is fine now.Sangeetha Santhiralingam

+1

Sangeetha Santhiralingam I guess it is for practice or an assignment. Make your own tools instead of using tools in the toolbox.

+1

me too i have that problems

0

Hello dear

0