-1

I am trying to make a simple program that shift the position of the first to the last until a: 1 2 3 4 5 6 Looks like: 6 5 4 3 2 1

IDK why the second for doesn´t work.

using namespace std;
int main() {
    int x[6], a = 6, safe = 0;
    cout<<"Value"<<endl;
    for (int i = 0; i < 6; ++i) {
        cin>>x[i];
    }

    for (int i = 0; i != 2; ++i) {
        safe = x[i];
        x[i] = x[a];
        x[a] = safe;
        a --;
    }

    for (int i = 0; i < 6; ++i) {
        cout<<"[ "<<x[i]<<" ]"<<endl;
    }

    return 0;
}
bastion9
  • 11
  • 5
  • If `a=6` on initial condition in the first iteration of your second loop, and your array `x `only has 6 elements, then `x[a]` is already out of bounds. What do you get with `a=5` ? – MFisherKDX Mar 11 '21 at 00:19
  • it's a reversal or mirroring, not a shift – phuclv Mar 11 '21 at 02:47

1 Answers1

-1

Problems:

  1. x[a] access an element out of bonds during the first iteration, what itself is Undefined Behaviour.
  2. for (int i = 0; i != 2; ++i) does not make sense at all. Why the condition would be i != 2.

Solution:

Instead of making yourself a lot of trouble you can just reverse the array with std::reverse (Documentation for std::reverse here).

If you want to make it manually it is easier than you think. Just replace the second for loop with this:

for (int i = 0; i < length/2; ++i)
        std::swap(x[i],x[length-i-1]);

This traverses the array with a single variable and swaps the values in the left with the values in the right.

Additional information:

  1. safe variable is never used. You should delete it.
  2. You may use std::array instead of raw C arrays (Documentation for std::array here).
  3. using namespace std; is considered a bad practice (More info here).

Full code:

#include <iostream>

int main() {
    constexpr int length = 6;
    int x[length];
    std::cout << "Value" << std::endl;
    for (int i = 0; i < length; ++i)
        std::cin >> x[i];

    for (int i = 0; i < length/2; ++i)
        std::swap(x[i],x[length-i-1]);

    for (int i = 0; i < length; ++i)
        std::cout<<"[ "<<x[i]<<" ]"<<std::endl;

    return 0;
}
Gary Strivin'
  • 908
  • 7
  • 20