# Problem with arrays

• January 21st, 2011, 02:00 AM
coorscollector
Problem with arrays
I am a beginner and my teacher assigned us a problem where we are given an array named arr. We are supposed to create a new array that only has the odd values from arr. This is my code:
Code Java:

```public int [] youMakeMeOdd(int [] arr) { int[] ans = new int[arr.length]; for (int i = 0; i<arr.length; i++) { if(arr[i] % 2 != 0) { ans[i] = arr[i]; } } return ans; }```
However, say for example that arr had only even integers to begin with. My new array will be filled with 0's.
But it is supposed to not have the zeros.

Say arr was {2,4,5,6}. My new array should be {5}. Instead it is{0,0,5,0}. I need a way to get rid of the zeros. Any help would be appreciated.
• January 21st, 2011, 02:25 AM
JavaHater
Re: Problem with arrays
you can make a count of how many odd integers there are first. After that you can initialize the ans array with that count size. Then go through the array again and store the odd number. Or you can use ArrayList if your teacher doesn't forbid.
• January 21st, 2011, 02:38 AM
coorscollector
Re: Problem with arrays
ArrayLists are forbidden so that's a no go. This might sound a little dumb, but how do I count the odd integers?
• January 21st, 2011, 03:50 AM
DanBrown
Re: Problem with arrays
First i would like to tell problem with your code ,see all the elements of the array are initalized with value o
when you define it.
Now you are adding lement whenever any odd no found so it could be in any index position within your array so
Quote:

ans[i] = arr[i];
this line is storing odd no at original index as in the input array.

Code :

```public int [] youMakeMeOdd(int [] arr) { int[] ans = new int[arr.length]; int k=0;   for (int i = 0; i<arr.length; i++) { if(arr[i] % 2 != 0) { ans[k] = arr[i]; k++;   } } return ans; }```
Quote:

Say arr was {2,4,5,6}. My new array should be {5}. Instead it is{0,0,5,0}. I need a way to get rid of the zeros. Any help would be appreciated.
In the modified code above
Output for this input will be {5,0,0,0}
now you can display elements upto first zero found.

for(int i=0;i<ans.length;i++){
System.out.println(ans[i]);
if(ans[i] == 0)
break;
}