
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reverse Array Elements In-Place in C++
Suppose we have an array with n different elements. We shall have to reverse the elements present in the array and display them. (Do not print them in reverse order, reverse elements in place).
So, if the input is like n = 9 arr = [2,5,6,4,7,8,3,6,4], then the output will be [4,6,3,8,7,4,6,5,2]
To solve this, we will follow these steps −
-
for initialize i := 0, when i < quotient of n/2, update (increase i by 1), do:
temp := arr[i]
arr[i] := arr[n - i - 1]
arr[n - i - 1] := temp
-
for initialize i := 0, when i < n, update (increase i by 1), do:
display arr[i]
Let us see the following implementation to get better understanding −
Example
#include <iostream> using namespace std; int main(){ int n = 9; int arr[n] = {2,5,6,4,7,8,3,6,4}; int temp; for(int i = 0; i<n/2; i++){ temp = arr[i]; arr[i] = arr[n-i-1]; arr[n-i-1] = temp; } for(int i = 0; i < n; i++){ cout << arr[i] << " "; } }
Input
9, {2,5,6,4,7,8,3,6,4}
Output
4 6 3 8 7 4 6 5 2
Advertisements