Call us at 0700-922-6559 or Click here

Write a function using reference variables as arguments to swap the values of a pair of integers.

#include <iostream>

using namespace std;

// Function to swap two integers using reference variables

void swap(int &x, int &y) {

  // Create a temporary variable to hold one of the values

  int temp = x;  // Store the value of x in temp

  // Swap the values using the references

  x = y;         // Assign the value of y to x

  y = temp;      // Assign the original value of x (stored in temp) to y

}

int main() {

  // Declare variables with names

  int Ram_marks = 85, Sita_marks = 92;

  cout << “Before swapping:\n”;

  cout << “Ram’s marks: ” << Ram_marks << endl;

  cout << “Sita’s marks: ” << Sita_marks << endl;

  // Call the swap function to exchange values

  swap(Ram_marks, Sita_marks);

  cout << “\nAfter swapping:\n”;

  cout << “Ram’s marks: ” << Ram_marks << endl;

  cout << “Sita’s marks: ” << Sita_marks << endl;

  return 0;

}

Output:

Before swapping:

Ram’s marks: 85

Sita’s marks: 92

After swapping:

Ram’s marks: 92

Sita’s marks: 85

Here’s a step-by-step explanation of the code:

1. Header and Namespace:

  • #include <iostream>: This line includes the iostream header file for input/output operations.
  • using namespace std;: This brings the std namespace into scope, allowing you to use elements like cin, cout, and endl without the std:: prefix.

2. Swap Function:

  • void swap(int &x, int &y): This declares a function named swap that takes two integer reference variables (x and y) as arguments. It doesn’t return a value (hence void).
  • int temp = x;: A temporary variable temp is created to store the value of x temporarily.
  • x = y;: The value of y is assigned to x, effectively overwriting x’s original value.
  • y = temp;: The original value of x (stored in temp) is assigned to y, completing the swap.

3. Main Function:

  • int main(): This is where program execution begins.
  • int Ram_marks = 85, Sita_marks = 92;: Two integer variables are declared and initialized with values.
  • cout << “Before swapping:…”;: The initial values of the variables are printed to the console.
  • swap(Ram_marks, Sita_marks);: The swap function is called, passing the variables Ram_marks and Sita_marks by reference. This means the function directly modifies the original variables.
  • cout << “After swapping:…”;: The swapped values of the variables are printed to the console.

return 0;: The program returns 0 to indicate successful execution.

Leave a Reply

Your email address will not be published. Required fields are marked *