Related Tags

c++
algorithm
swap
communitycreator

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

Sarah Tanveer

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;
}

### 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;
}

RELATED TAGS

c++
algorithm
swap
communitycreator

CONTRIBUTOR

Sarah Tanveer
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time