In this tutorial you will learn about the C++ Programs to Reverse Array Element Using Function and its application with practical example.
C++ Programs to Reverse Array Element Using Function
In this tutorial, we will learn to create a C++ program that will Reverse Array Element Using Function using C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- For loop in C++ Programming.
- Functions in C++ Programming.
Reversing of the array.
The array stores multiple elements in a single variable using the different index values. All the array operations are performed on the index values for manipulation in an array. In this tutorial, we will reverse the elements of the array from start to end.
1 2 3 4 5 6 7 8 9 10 11 12 |
For example :- Take an array A[]={ a , b , c , d } The index of values are a = 0; b = 1; c = 2; d = 3; now we will reverse that array by putting the first value to last and so on. By reversing the index values. it means new array will ne A[] = { d , c , b , a }; |
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
STEP 1: START STEP 2: INITIALIZE arr[] = { 1, 2, 3, 4, 5 } STEP 3: length= sizeof(arr)/sizeof(arr[0]) STEP 4: PRINT ARRAY NORMAL STEP 5: REVERSING ARRAY STEP 6: PRINT "REVERSE ORDER OF ARRAY IS AS FOLLOWS" STEP 7: RETURN 0. STEP 8: END. |
Programs to Reverse Array Element Using Function:-
In the program, First, we will initialize the elements of an array. Then we will reverse that array using C++ Programming Language.
Program:-
To Reverse Array Element Using Function
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> #include <algorithm> using namespace std; // Utility function to print contents of an array void print(int arr[], int n) { for (int i = 0; i < n; i++) { cout << arr[i] << " "; } } // Utility function to reverse elements of an array void reverse(int arr[], int n) { reverse(arr, arr + n); } int main() { //declaring the variables for the program. int arr[] = { 1, 2, 3, 4, 5 }; //finding the size of array. int n = sizeof(arr)/sizeof(arr[0]); //Printing the normal array. cout << "Elements in array " ; for (int i = 0; i < n; i++) { cout << arr[i] << " " <<endl; } //passing the array to the reverse function reverse(arr, n); //Printing the out array cout << "Reverse Elements in array " ; print(arr, n); return 0; } |
Output:-
In the above program, we have first initialized the required variable
- arr = it will hold the elements in an array.
- n = it will hold the number of elements in an array.
- i = it will hold the integer value to control the array.
Printing elements of the array
Calling of user-defined function in program.
Program Code for reverse function.
Program Code for Print function.