Reversing with swap coderinme

Reversing with swap coderinme

Now we shall write a program in C++ so as to get an array of elements from the user, scan those elements, swap if requires and thus to rearrange the array in its reverse form.
write a swap function template in C++ that can swap the values of two
variables of any data type using the above swap function template.
Solution:

#include<iostream.h>
#include<conio.h>
template<class T>
void swap(T &a, T &b)
{
T temp=a;
a=b;
b=temp;
}
int main()
{
int i,n;
int array[50];
cout<<endl<<"Enter the size of array: ";
cin>>n;
for(i=0;i<n;i++)
{
cout<<"enter the "<<i+1<<" element of array: ";
cin>>array[i];
}
cout<<endl<<"Array before reversing is: "<<endl;
for(i=0;i<n;i++)
{
cout<<" "<<array[i];
}
cout<<endl<<"Array after reversing is: "<<endl;
for(i=0;i<n/2;i++)
{
swap(array[i],array[4-i]);
}
for(i=0;i<n;i++)
{
cout<<" "<<array[i];
}
getch();
return 0;
}

For more programs in C++, visit our C++ Coder Archives

Reversing with swap coderinme

All rights reserved. No part of this Post may be copied, distributed, or transmitted in any form or by any means, without the prior written permission of the website admin, except in the case of brief quotations embodied in critical reviews and certain other noncommercial uses permitted by copyright law. For permission requests, write to the owner, addressed “Attention: Permissions Coordinator,” to the admin @coderinme

Leave a reply:

Your email address will not be published.