Reversing an array – Computer Sir Ki Class

Code Learning #CPP#2506

## Reversing an array

Reversing an integer array using the swapping of members around midpoint.

## Learning Objectives

• Learning to reverse an array using the swapping around the mid point of the array.

## Source Code

 #include using namespace std; int main() { int a[]={1,2,3,4,5}; int cnt=sizeof(a)/sizeof(a[0]); cout<<"array members before reversal are :"<

## Run Output

``````array members before reversal are :
1 2 3 4 5
array members after reversal are :
5 4 3 2 1``````

## Code Understanding

int a[]={1,2,3,4,5}; //Array initialisation with 5 integer literal constants.
int cnt=sizeof(a)/sizeof(a[0]); //Array member count finding using the technique given at #2502
cout<<“array members before reversal are :”<<endl; //Initial prompt before printing array.
for(int i=0;i<cnt;++i) cout<<a[i]<<” “;  //Array printing before reversal

for(int i=0;i<cnt/2;++i)
Array Reversal loop runs till mid point only. If cnt is even then it will run exactly till midpoint and if odd it will run just before mid point. This is due to integer division. If it has five members 5/2 = 2 (integer division). So first two members will be interchanged with last two. If it has 6 members 6/2 = 3. First 3 members will be interchanged by last 3.
{
int temp=a[i];       //Shifting left side member to temp variable.
a[i]=a[cnt-i-1];    //Shifting right of array computed in each iteration by cnt-i-1 to left side member
a[cnt-i-1]=temp;  //Temp is put back to right side of array
}
cout<<endl<<“array members after reversal are :”<<endl;
for(int i=0;i<cnt;++i) cout<<a[i]<<” “;
Printing after the reversal using the swap is complete.

## Notes

• This logic of array reversal works for any data type, char, long, float, double etc.
• The swapping technique is as explained in the codesheet #2493

## Common Errors

• Student make error in the swapping order. Stick to the order given in this problem.

Suggested Filename(s): arr-rev.cpp

sunmitra| Created: 11-Jan-2018 | Updated: 12-Jan-2018|

×