Problems:
x[a]
access an element out of bonds during the first iteration, what itself is Undefined Behaviour.
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:
safe
variable is never used. You should delete it.
- You may use
std::array
instead of raw C arrays (Documentation for std::array
here).
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;
}