Reversing an array – CSKC
Sign In

Search

Code Learning #CPP#2506    siteicon   siteicon  

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

TC++ #2506

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

  Related ( ? ) :

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



Share

Created: 11-Jan-2018 23:54 | Updated: 12-Jan-2018 00:08|