In this tutorial, we will see how to reverse an array in C++ using functions. It is essential to understand the concept of arrays and functions in C++ before attempting this tutorial. Reversing an array means changing the order of its elements so that the first element becomes the last, the second element becomes the second last, and so on.
Step 1: Include required libraries
First, include the required libraries. In this case, we only need the iostream
library for input/output operations.
1 |
#include |
Step 2: Declare and define the function
Declare the function that will reverse the array. The function takes two parameters, the array and its size, as inputs.
1 |
void reverseArray(int arr[], int size); |
Define the function by creating a new loop. In the loop, swap the elements from the beginning with the elements from the end of the array, and continue till the array is reversed.
1 2 3 4 5 6 7 |
void reverseArray(int arr[], int size) { for (int i = 0; i < size / 2; i++) { int temp = arr[i]; arr[i] = arr[size - 1 - i]; arr[size - 1 - i] = temp; } } |
Step 3: Implement the main function
Implement the main function where you will take the array as input, display the original array, call the reverseArray
function, and display the reversed array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
int main() { int size; std::cout << "Enter the size of array: "; std::cin >> size; int arr[size]; std::cout << "Enter the elements of the array: "; for (int i = 0; i < size; i++) { std::cin >> arr[i]; } std::cout << "Original array: "; for (int i = 0; i < size; i++) { std::cout << arr[i] << " "; } reverseArray(arr, size); std::cout << "\nReversed array: "; for (int i = 0; i < size; i++) { std::cout << arr[i] << " "; } return 0; } |
Complete Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> void reverseArray(int arr[], int size); void reverseArray(int arr[], int size) { for (int i = 0; i < size / 2; i++) { int temp = arr[i]; arr[i] = arr[size - 1 - i]; arr[size - 1 - i] = temp; } } int main() { int size; std::cout << "Enter the size of array: "; std::cin >> size; int arr[size]; std::cout << "Enter the elements of the array: "; for (int i = 0; i < size; i++) { std::cin >> arr[i]; } std::cout << "Original array: "; for (int i = 0; i < size; i++) { std::cout << arr[i] << " "; } reverseArray(arr, size); std::cout << "\nReversed array: "; for (int i = 0; i < size; i++) { std::cout << arr[i] << " "; } return 0; } |
Output:
Enter the size of array: 5 Enter the elements of the array: 1 2 3 4 5 Original array: 1 2 3 4 5 Reversed array: 5 4 3 2 1
Conclusion:
In this tutorial, we have learned how to reverse an array in C++ using a function. We have seen how to declare and define the function along with its implementation within the main function. This is a fundamental and essential concept in C++ programming that has various practical applications.