How to move positions within an array?
Posted
by
Jade Mulholland
on Stack Overflow
See other posts from Stack Overflow
or by Jade Mulholland
Published on 2012-11-05T03:51:30Z
Indexed on
2012/11/05
5:00 UTC
Read the original article
Hit count: 158
A program that simply moves array elements.
Two variables: userInputVariable and blankSpaceVariable.
I have a 2D array named table. Defined as table[userInputVariable + 1][6]
I am printing out this array in a table format, and the far left column is numbered by whatever number the user entered at the beginning of the program.
I then ask the user where they would like to enter a blank space within the array. This blank space acts like a divider for all the other information in the array.
For example, if the user enters 10 at the start for the userInputVariable, and then enters 5 for the blank space. Once printed, the numbers should go like this:
1, 2, 3, 4, --, 5, 6, 7, 8, 9, 10.
My plan has been to create a for loop and try to move all the numbers in the array back a position starting from the blank space variable.
What I currently have, but does not work:
for (int i = blankSpaceVariable; i < table.length - 1; i++)
{
table[i] = table[i + 1];
}
table[blankSpaceVariable] = "--";
With my current code, the numbers go like this:
1, 2, 3, 4, 6, 7, 8, 9, 10
Tried completing this a few different ways also, but the other info within my 2D array didn't move with the numbers. So I thought that this approach can hopefully move all the info within my 2D array down, and make way for a blank section.
All help is greatly appreciated!
© Stack Overflow or respective owner