+ 1

How can i know what's the last position with a value on arrays?

so i have to do a program that should take the value you give and assign it to a position in the array, but how can i know what's the next position avaible? (example: a = {1,2,3,0,0,0,0} the zeros are the avaible positions but how do i get my program to recgonize that? and assign the number i want to that position?) Thanks

19th Sep 2017, 1:09 AM
Juan Felipe Jaramillo
Juan Felipe Jaramillo - avatar
5 Answers
+ 5
Excellent question. Break down: * Check if the value of an element in the array is 0. * If it is, that's the position you add the number into the array. * If it isn't 0, check the next position. This is a linear seach. Here's an example code: final int NUM = 5; // the number to add into the array int[] theArray = {4,0,2,1,0,0}; for(int i = 0; i < theArray.length; i++) if(theArray[i] == 0) { theArray[i] = NUM; break; } // Search the array for an empty space, if it's there, set the value avcordingly and exit the loop Now the array is: 4,5,2,1,0,0
19th Sep 2017, 1:30 AM
Rrestoring faith
Rrestoring faith - avatar
+ 4
Yes, it would. That can be a problem. You could keep track of how many things you've added into the array, leaving the spaces that came before that number the way they are: int arraySize = 3; int[] myArray = {0, 6, 3, 0, 0}; final int NUM = 4; myArray[arraySize++] = NUM; However, now you will no longer be able to have an array like: {3, 0, 5, 8, 2, 0} Where the first 0 is the empty position and the last 0 is just a regular 0 that you want to use. So, if that's an issue I'd then suggest that you use an arrayList instead of an array. Or, use some other value like -1 to indicate an empty spot in the array. (And initially fill it with -1's).
19th Sep 2017, 1:39 AM
Rrestoring faith
Rrestoring faith - avatar
+ 3
xD
19th Sep 2017, 1:41 AM
Rrestoring faith
Rrestoring faith - avatar
+ 1
Thanks a lot, but what if i wanna assign 0 to a position? wouldn't this code change it for the next number i assign?
19th Sep 2017, 1:33 AM
Juan Felipe Jaramillo
Juan Felipe Jaramillo - avatar
+ 1
Thanks a lot, you really saved my life
19th Sep 2017, 1:40 AM
Juan Felipe Jaramillo
Juan Felipe Jaramillo - avatar