Changing and shifting of elements in 1D array

Just taught myself about arrays and now I have this problem:

suppose if I have a any random array ike this:

| 12 | 13 | 7 | 9 | 7 |


now if i want to assign 0 to every 7 then it would look like this

| 12 | 13 | 0 | 9 | 0 |


and shift all the zeroes to the left without changing any other order like this

| 0 | 0 | 12 | 13 | 9 |  



and/or also to the right like this

| 12 | 13 | 9 | 0 | 0 |


what should i do???
Last edited on
Imagine if you had 2 arrays. One array is your original random array and the other is the output array.
Original:
| 12 | 13 | 7 | 9 | 7 |

Output:
| ?? | ?? | ?? | ?? | ?? |

The question marks represent uninitialized space in memory.

Let us also have an index variable for each array for keeping track of progress:
1
2
int ind_orig = 0;
int ind_out = 0;

I am going to walk through the case of shifting to the right, so the final output should be:
| 12 | 13 | 9 | 0 | 0 |

I am going to use the same number, 7, that you mentioned in your example.
int_orig is currently 0 , so we check to see if the first element of the original array is equal to 7. 12 is not equal to 7, so we assign 12 to the output array at the spot indexed by ind_out. We also increment both indexes. The next number at index int_orig is 13, which does not equal 7. We repeat the same as earlier. Assign 13 to output array, and increment both indexes. Now we encounter a 7, in this case 7 does equal 7. Only ind_orig is incremented, and nothing is done to the output array. This process continues until the end of the original array is reached. At that point the output array looks like this:
| 12 | 13 | 9 | ?? | ?? |

Now all that is left to do is assign 0s until the end of output array is reached.
I hope this helps :)
Last edited on
thanks man.....
Topic archived. No new replies allowed.