103,981 views
12 votes
12 votes
Write the removeevens() method, which receives an array of integers as a parameter and returns a new array of integers containing only the odd numbers from the original array. the main program outputs values of the returned array.

hint: if the original array has even numbers, then the new array will be smaller in length than the original array and should have no blank element.
ex: if the array passed to the removeevens() method is [1, 2, 3, 4, 5, 6, 7, 8, 9], then the method returns and the program output is:
[1, 3, 5, 7, 9]
ex: if the array passed to the removeevens() method is [1, 9, 3], then the method returns and the program output is:
[1, 9, 3]
lab: remove all even numbers from an array
labprogram.java l.
1 import java.util.arrays;
2
3 public class labprogram {
4
5 public static int[] removeevens(int [] nums) {
6
7
8 }
9
10 public static void main(string[] args) {
11
12 int [] input {1,2,3,4,5,6,7,8,9};
13 int [] result = removeevens(input);
14
15 // helper method arrays.tostring() converts int[] to a string
16 system.out.println(arrays.tostring(result)); // should print [1, 3, 5, 7, 9]
17 }
18 }

User Sameer Shah
by
2.4k points

1 Answer

11 votes
11 votes

Answer:

import java.util.*;

import java.util.Arrays;

public class LabProgram

{

// called function

public static int[] removeEvens(int [] nums)

{

// calculates the length of array

int len = nums.length;

int j=0;

// loop to keep count how many odd are there in array

for(int i=0;i<len;i++)

{

// condition for odd

if(nums[i]%2!=0)

{

// keeps count of odd

j++;

}

}

// declaration of array for odd nums

int newarray[] = new int[j];

j = 0;

// loop

for(int i=0;i<len;i++)

{

// condition for odd

if(nums[i]%2!=0)

{

// assigning odd number to new array

newarray[j] = nums[i];

// increment of j

j++;

}

}

// returning new array

return newarray;

}

// main program

public static void main(String[] args)

{

// array declaration

int [] input = {1,2,3,4,5,6,7,8,9};

// calling a function, passing the paramtere

int [] result = removeEvens(input);

//

System.out.println(Arrays.toString(result));

}

}

Step-by-step explanation:

User Deko
by
2.4k points