简体   繁体   中英

Reverse Contents in Array

I have an array of numbers that I am trying to reverse. I believe the function in my code is correct, but I cannot get the proper output.

The output reads: 10 9 8 7 6. Why can't I get the other half of the numbers? When I remove the "/2" from count, the output reads: 10 9 8 7 6 6 7 8 9 10

void reverse(int [], int);

int main ()
{
   const int SIZE = 10;
   int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

   reverse(arr, SIZE);
   return 0;
}
void reverse(int arr[], int count)
{
   int temp;
   for (int i = 0; i < count/2; ++i)
   {
      arr[i] = temp;
      temp = arr[count-i-1];
      arr[count-i-1] = arr[i];
      arr[i] = temp;

      cout << temp << " ";
   }
}

This would be my approach:

#include <algorithm>
#include <iterator>

int main()
{
  const int SIZE = 10;
  int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  std::reverse(std::begin(arr), std::end(arr));
  ...
}

The line

arr[i] = temp;

is wrong. (On the first iteration of your loop it sets arr[i] to an undefined value; further iterations set it to an incorrect value.) If you remove this line, your array should be reversed correctly.

After that, you should move the code which prints the reversed array into a new loop which iterates over the whole list. Your current code only prints the first count/2 elements.

int temp, i;
for (i = 0; i < count/2; ++i) {
    temp = arr[count-i-1];
    arr[count-i-1] = arr[i];
    arr[i] = temp;
}
for (i = 0; i < count; ++i) {
    cout << arr[i] << " ";
}

Both answers look correct to me.

  1. The first arr[i] = temp; should be removed

  2. You should do a second loop to print all elements, not just half the array. The loop that does the reverse doesn't need to print it.

I would use the reverse() function from the <algorithm> library.

Run it online: repl.it/@abranhe/Reverse-Array

#include <iostream>
#include <algorithm>
using namespace std;

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

  reverse(begin(arr), end(arr));

  for(auto item:arr)
  {
    cout << item << " ";
  }
}

Output:

10 9 8 7 6 5 4 3 2 1

Hope you like this approach.

您不是在打印数组,而是在打印temp的值 - 这只是数组的一半......

void reverse(int [], int);
void printarray(int [], int );
int main ()
{
    const int SIZE = 10;
    int arr [SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

    cout<<"Before reverse\n";
    printarray(arr, SIZE);
    reverse(arr, SIZE);
    cout<<"After reverse\n";
    printarray(arr, SIZE);

    return 0;
}

void printarray(int arr[], int count)
{
    for(int i = 0; i < count; ++i)
        cout<<arr[i]<<' ';

    cout<<'\n';
}

void reverse(int arr[], int count)
{
   int temp;
   for (int i = 0; i < count/2; ++i)
   {
      temp = arr[i];
      arr[i] = arr[count-i-1];
      arr[count-i-1] = temp;
   }
}

The solution to this question is very easy: Vectors

std::vector<int> vector;
for(int i = 0; i < 10;i++)
{
    vector.push_back(i);
}
std::reverse(vector.begin(), vector.end());

Voila! You are done! =)

Solution details:

This is the most efficent solution: Swap can't swap 3 values but reverse definitely can. Remember to include algorithm. This is so simple that the compiled code is definitely not needed.

I think this solves the OP's problem

If you think there are any errors and problems with this solution please comment below

As a direct answer to your question: Your swapping is wrong

void reverse(int arr[], int count){
   int temp;
   for(int i = 0; i < count/2; ++i){
      arr[i] = temp; // <== Wrong, Should be deleted
      temp = arr[count-i-1];
      arr[count-i-1] = arr[i];
      arr[i] = temp;
    }
}

assigning arr[i] = temp causes error when it first enters the loop as temp initially contains garbage data and will ruin your array, remove it and the code should work well.

As an advice, use built-in functions whenever possible:

  • In the swapping you could just use swap like std::swap(arr[i], arr[count-i-1])
  • For the reverse as a whole just use reverse like std::reverse(arr, arr+count)

I am using C++14 and reverse works with arrays without any problems.

First of all what value do you have in this pice of code? int temp; ? You can't tell because in every single compilation it will have different value - you should initialize your value to not have trash value from memory. Next question is: why you assign this temp value to your array? If you want to stick with your solution I would change reverse function like this:

void reverse(int arr[], int count)
{
    int temp = 0;
    for (int i = 0; i < count/2; ++i)
    {
        temp = arr[count - i - 1];
        arr[count - i - 1] = arr[i];
        arr[i] = temp;
    }

    for (int i = 0; i < count; ++i)
    {
        std::cout << arr[i] << " ";
    }
}

Now it will works but you have other options to handle this problem.

Solution using pointers:

void reverse(int arr[], int count)
{
    int* head = arr;
    int* tail = arr + count - 1;
    for (int i = 0; i < count/2; ++i)
    {
        if (head < tail)
        {
            int tmp = *tail;
            *tail = *head;
            *head = tmp;

            head++; tail--;
        }
    }

    for (int i = 0; i < count; ++i)
    {
        std::cout << arr[i] << " ";
    }
}

And ofc like Carlos Abraham says use build in function in algorithm library

#include "stdafx.h"
#include <iostream>
using namespace std;

void main()
{
    int n, i;
    cout << "n = ";
    cin >> n;
    int *a = new int[n];
    int *b = new int[n];
    for (i = 0; i < n; i++)
    {
        cout << "a[" << i << "]= ";
        cin >> a[i];
    }
    for (i = 0; i < n; i++)
    {
        b[i] = a[n - 1 - i];
    }
    for (i = 0; i < n; i++)
    {
        cout << b[i];
    }
}
Procedure :

 1.Take an array.

 2.Then by default function reverse(array_name, array_name + size) .
  reverse(array_name, array_name + size) function exits in algorithm.h header file.

 3.Now print the array. 

 N.B  Here we use new and delete for dynamic memory allocation.

C++ implementation :


#include<bits/stdc++.h>
using namespace std;


int main()
{
   int n;
   cin>>n;

   int *arr = new int[n];


   for(int i=0; i<n; i++)  cin>>arr[i];

   reverse(arr, arr+n);

   for(int i=0; i<n; i++)    cout<<arr[i]<<" ";

   delete[] arr;

   return 0;
}

First of all you assign temp to array elemets and you should remove arr[i] = temp; statment. Next problem is that you are printing temp variable which shows only half of array elements(in your for loop). If you don't want to use STL vectors I would suggest this solution:

#include <iostream>

void reverseArray(int userArray[], int size);

void printArray(int userArray[], int size);

int main(int arg, char**argv) {

    int arr[]{ 1,2,3,4,5,6,7,8,9,10 };
    int sizeOfArray = sizeof(arr) / sizeof(arr[0]);

    reverseArray(arr, sizeOfArray);
    printArray(arr, sizeOfArray);

    system("pause");
    return(0);
}

void reverseArray(int userArray[], int size) {

    int* ptrHead = userArray;
    int* ptrTail = userArray + (size-1);

    while (ptrTail > ptrHead) {
        int temp = *ptrHead;
        *ptrHead = *ptrTail;
        *ptrTail = temp;

        ptrHead++;
        ptrTail--;
    }
}

void printArray(int userArray[], int size) {
    for (int i = 0; i < size; i++) {
        std::cout << userArray[i] << " ";
    }
}

Your loop will run only for count/2 times. So it will not print the whole array.

Also, temp=ar[i] should be used instead of ar[i]=temp as value of ar[i] is not getting stored anywhere in the latter statement, hence it is getting destroyed.

for(i=0;i<((s3)/2);i++)
{         
    z=s2[i];
    s2[i]=s2[(s3-1)-i];
    s2[(s3-1)-i]=z;
}

I would try to using pointers to solve this problem:

#include <iostream>

void displayArray(int table[], int size);

void rev(int table[], int size);


int main(int argc, char** argv) {

    int a[10] = { 1,2,3,4,5,6,7,8,9,10 };

    rev(a, 10);
    displayArray(a, 10);

    return 0;
}

void displayArray(int table[], int size) {
    for (int i = 0; i < size; i++) {
        std::cout << table[i] << " ";
    }
    std::cout << std::endl;
}

void rev(int table[], int size) {

    int *start = table;
    int *end = table + (size - 1);

    for (int i = 0; i < size; i++) {

        if (start < end) {
            int temp = *end;
            *end = *start;
            *start = temp;
        }

        start++;
        end--;
    }
}

my approach is swapping the first and last element of the array

int i,j;
for ( i = 0,j = size - 1 ; i < j ; i++,j--)
{  
    int temp = A[i];
    A[i] = A[j];
    A[j] = temp; 
}

You can use the following example to reverse the contents in an array:

#include <iostream>

int main()
{
    int n, x;

    // order value for var x
    cin >> x;  

    // create array and the value for array is value var x
    int arr[x];

    // loop for insert values for array by reverse  
    for(int i=x; i > 0; i--) {

        // var i is number of elements in array 
        cin >> n;
        arr[i - 1] = n;
    }

    // show element in array
    for(int l = 0; l < x; l++) {
        cout<<arr[l]<<endl;
    }

    return 0;        
}

try this can you better fell comparing to another codes.

using namespace std;
int main() {
    int a[5]={4,6,3,5,9};
    for(int i=4;i>=0;i--) {
        cout<<"\n"<<a[i];
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM