In this tutorial, we will see how we can reverse an array in C++. So here goes the code:
Here when the 'reverseArray' function is called, it takes in the array and its size as the parameter. After that we set 'l' as left index and 'r' as right index. The while loop starts swapping the array with given indices, where the 'l' increases and 'r' decreases after each iteration. Thus when they reach the middle index two things happen:
1. If n is odd, the array has a mid point which is (n/2+1). In that case l=r and the loop stops.
2. If n is even, the array does not have a middle point, so we give the condition 'l<r' inside the while loop, so that the 'l' index does not increment after 'r'.
Output:
Original Array: 1,2,3,4,5,6,7,8,9.
Reversed Array: 9,8,7,6,5,4,3,2,1.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
void reverseArray(int arr[], int n); | |
void printArray(int arr[], int n); | |
void reverseArray(int arr[], int n) { | |
int l = 0; int r = n-1; | |
while(l != r && l<r) { | |
swap(arr[l++], arr[r--]); } | |
} | |
void printArray(int arr[], int n) { | |
for(int i = 0; i<n; i++) { | |
cout<<arr[i]<<" "; }} | |
int main(){ | |
int arr[] = {1,2,3,4,5,6,7,8,9}; | |
int n = sizeof(arr)/sizeof(arr[0]); | |
cout<<"Original Array: "; | |
printArray(arr, n); | |
cout<<"\nReversed Array: "; | |
reverseArray(arr, n); | |
printArray(arr, n); | |
return 0; | |
} |
Here when the 'reverseArray' function is called, it takes in the array and its size as the parameter. After that we set 'l' as left index and 'r' as right index. The while loop starts swapping the array with given indices, where the 'l' increases and 'r' decreases after each iteration. Thus when they reach the middle index two things happen:
1. If n is odd, the array has a mid point which is (n/2+1). In that case l=r and the loop stops.
2. If n is even, the array does not have a middle point, so we give the condition 'l<r' inside the while loop, so that the 'l' index does not increment after 'r'.
Output:
Original Array: 1,2,3,4,5,6,7,8,9.
Reversed Array: 9,8,7,6,5,4,3,2,1.
No comments:
Post a Comment