Reversing the elements of an array


using namespace std;
int main()
{
int a[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};

for(int k = 0; k < 10; k++)
{
int temp = a[k]; // store the first element value in temp
a[k] = a[9-k]; // store the last element value in the first element
a[9-k] = temp; // store temp in the last element
}

return 0;
}
Found on google:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>

#define ARR_SIZE 11

int main()
{
    int arr[ARR_SIZE] = {1,2,3,4,5,6,7,8,9,0,11};
    int i = 0;

    // Dispay the content of the array initially
    cout<<"Array content as input"<<endl;
    for(i=0;i<ARR_SIZE;i++)
        cout<<arr[i]<<"\t";
    cout<<endl;

    // Swap the array elements each from the first and the last.
    // It handles automatically the odd and the even no of elements
    for(i=0;i<ARR_SIZE/2;i++)
    {
        int temp = arr[i];
        arr[i] = arr[ARR_SIZE - i-1];
        arr[ARR_SIZE - i-1] = temp;
    }

    // Dispay the content of the array after the swap.
    cout<<"Array content as output"<<endl;
    for(i=0;i<ARR_SIZE;i++)
        cout<<arr[i]<<"\t";
    cout<<endl;

    return 0;
}
u just want to reverse the elements of an array??
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream.h>
#include <conio.h>
void main ()
{
  int a[5],t[5];                  //You can put any number u want!
  for(int i=0;i<5;i++)//Instead of i<5,u can put the max.size of the array u want
  cin>>a[i];
  for(i=0;i<5;i++)
  t[i]=a[4-i];
  for(i=0;i<5;i++)
  a[i]=t[i];
  for(i=0;i<5;i++)
  cout<<a[i];
  getch();
}

just thought about this on spot... dobt get annoyed of the saaame loop header ;)


Last edited on
It is enough to write one line.:)

std::reverse( std::begin( a ), std::end( a ) );

If you want to print the array in the reverse order then you can write the following line:)

std::reverse_copy( std::begin( a ), std::end( a ), std::ostream_iterator<int>( std::cout, " " ) );
Last edited on
Topic archived. No new replies allowed.