#include <iostream>
using namespace std;
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
swap(arr[0], arr[4]);
for (int i = 0; i < 5; i++) {
cout << arr[i] << " ";
}
return 0;
}
Explanation of the Code
- The code includes the necessary header file for input-output operations and defines the standard namespace.
- A function named
swap
is declared to swap the values of two integers using reference parameters. - Inside the
swap
function, a temporary variable temp
is used to hold the value of the first integer. - The value of the first integer
x
is then assigned the value of the second integer y
. - Finally, the value of the second integer
y
is assigned the value of the temporary variable temp
. - In the
main
function, an integer array arr
is declared and initialized with values {1, 2, 3, 4, 5}. - The
swap
function is called to swap the values at index 0 and index 4 of the array arr
. - A loop is used to print the elements of the array
arr
after the swap operation. - The output will be: 5 2 3 4 1