I don't want to reverse or shift the array. What I want is to write the array from right to left.
I did something like
int arr[5] = {0};
for (int i = 0; i < 5; i )
{
cout << "enter a number : ";
cin >> arr[i];
for (int j = 0; j < 5; j )
{
if (arr[j] != 0)
{
cout << arr[j] << " ";
}
else
cout << "X ";
}
cout << endl;
}
and on the output screen I see this
enter a number : 5
5 X X X X
enter a number : 4
5 4 X X X
enter a number : 3
5 4 3 X X
enter a number : 2
5 4 3 2 X
enter a number : 1
5 4 3 2 1
Press any key to continue . . .
but i want to see this
enter a number : 5
X X X X 5
enter a number : 4
X X X 5 4
enter a number : 3
X X 5 4 3
enter a number : 2
X 5 4 3 2
enter a number : 1
5 4 3 2 1
Press any key to continue . . .
how can I do that?
I will be glad if you help.
CodePudding user response:
Just change the inner for loop for example the following way
int j = 5;
for ( ; j != 0 && arr[j-1] == 0; --j )
{
std::cout << 'X' << ' ';
}
for ( int k = 0; k != j; k )
{
std::cout << arr[k] << ' ';
}
CodePudding user response:
I think you are trying to write into the last index each time, and then move each number backwards in the array?
To write into the last index use cin >> arr[4]. Then After printing out the array copy each value into the previous index. Make sure that your copy only when the J index is less than 4
int arr[5] = {0};
for (int i = 0; i < 5; i )
{
cout << "enter a number : ";
//write into the last position
cin >> arr[4];
for (int j = 0; j < 5; j )
{
if (arr[j] != 0)
{
cout << arr[j] << " ";
}
else
cout << "X ";
//don't go out of bounds. This should move each number to the previous index
if(j<4){
arr[j]=arr[j 1];
}
}
cout << endl;
}