0 votes
99 views
in Theory by (115 points)
edited
Write a program of swap using function (C++)

1 Answer

0 votes
by (98.9k points)
edited by
 
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

Related questions

0 votes
1 answer 103 views

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

537 users

...