How to swap two elements in 1D array in C++

In this shot, we will learn how to swap two elements in a one-dimensional arraythe simplest form of array in C++. It is a group of elements that have the same datatype and same name..

Swapping 3 and 1

Code

Example 1: Manually swapping elements

In this algorithm, we use a temporary variable to swap the elements.

  1. The value of the first element (arr[0]) is stored in temp.

  2. The value of the second index (arr[2]) is then assigned to the first index (arr[0]).

  3. The value of temp is then assigned to the second index (arr[2]).

#include <iostream>
using namespace std;
// user defined function to print array
void printArr (int arr[], int size) {
for(int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
// declare array
const int size = 5;
int arr[size] = {5, 2, 3, 4, 1};
// temp variable to aid in swapping
int temp;
cout << "Original array: ";
printArr(arr, size);
// swapping first and last element
temp = arr[0];
arr[0] = arr[size - 1];
arr[size - 1] = temp;
cout << "Array with first and last element swapped: ";
printArr(arr, size);
return 0;
}
  • Lines 5-10: We defined a function with the name of printArr(), which will iterate over the array and print all its indexes.

  • Line 16: We defined an array with the name of arr[] and and size of 5.

  • Lines 25-27: We swapped the first and last values of the array by temporarily storing the value at index 0 in an temp variable then assigning the value at the last index to index 0, and finally placing the temp variable stored value at the last index.

Example 2: Using std::swap() to swap elements

The built-in swap() function can swap two values in an array.


template <class T> void swap (T& a, T& b);

The swap() function takes two arguments of any data typethis specifies the type of data that a variable can store, such as integer, floating, or character, etc., i.e., the two values that need to be swapped.

Return value

This function returns nothing.

#include <iostream>
using namespace std;
// user defined ftn to print array
void printArr (int arr[], int size) {
for(int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
// declare array
const int size = 5;
int arr[size] = {5, 2, 3, 4, 1};
// temp variable to aid in swapping
int temp;
cout << "Original array: ";
printArr(arr, size);
// swapping first and last element
swap(arr[0], arr[size - 1]);
cout << "Array with first and last element swapped: ";
printArr(arr, size);
return 0;
}
  • Lines 5-10:We defined the printArr() in a similar way we used in the previous example.

  • Line 25: We used the built-in swap() function provided by the C++ standard library. We're using it to swap the values of arr[0] and arr[size - 1], which effectively swaps the first and last elements of the array arr.

Free Resources