menu search
brightness_auto
more_vert
Write a program of swap using function (C++)
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike

1 Answer

more_vert
 
verified
Best answer
#include <iostream>
using namespace std;

void swap(int& x, int& y) {
 int temp = x;
 x = y;
 y = temp;
}

int main() {
 int a = 10;
 int b = 20;

 cout << "Before swapping: a = " << a << ", b = " << b << endl;

 swap(a, b);

 cout << "After swapping: a = " << a << ", b = " << b << endl;

 return 0;
}

In this program, we define a function swap() that takes two integer references x and y as input, and swaps their values using a temporary variable temp.

In the main() function, we define two integers a and b with initial values of 10 and 20, respectively. We then call the swap() function with a and b as arguments, which swaps their values.

Finally, we print the values of a and b before and after swapping to verify that the swapping operation worked correctly.

I hope this helps!


Program can be found here :


https://onlinegdb.com/ynfLO1363


image

thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike

Related questions

thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
0 answers
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
0 answers
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
1 answer

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

648 users

...