Java Program to Delete All the Negative Elements from the Array

In the previous article, we have seen Java Program to Find the Indexes of Element ‘0’ Present in Array

In this article we will see how to delete all the negative elements from an array.

Java Program to Delete All the Negative Elements from the Array

Array is a data structure which stores a fixed size sequential collection of values of single type. Where with every array elements/values memory location is associated. Each array elements have it’s own index where array index starts from 0.

In Array set of variables referenced by a single variable name and it’s array index position. It is also called as a container object which contains elements of similar type.

Declaration of an array:

dataType[] arrayName; (or)                              //Declaring an array
dataType []arrayName; (or)
dataType arr[];

Instantiation of an Array:

arrayName = new datatype[size];                    //Allocating memory to array

Combining both Statements in One:

dataType[] arrayName = new dataType[size] //Declaring and Instantiating array

Initialization of an Array:

arrayName[index-0]= arrayElement1             //Initializing the array

...

arrayName[index-s]= arrayElementS

Combining all Statements in One:

dataType arrayName[ ]={e1,e2,e3};               //declaration, instantiation and initialization

Let’s see different ways how to delete all negative elements from an array.

Method-1: Java Program to Delete All the Negative Elements from the Array Without Using an Extra Array

Approach:

  • Create scanner class object.
  • Ask user for input of array length.
  • Initialize the array with given size.
  • Ask the user for array elements.
  • Display the original array arr[].
  • Now call deleteNegative() user defined method.
  • Inside this method declare a variable 'p'=0
  • Then iterate the array(by for loop) and check if any positive element is found then store that in arr[p++]. Means we are not storing negative elements.
  • After the completion of the iteration(for loop) we will see arr[] now contains all positive numbers where 'p' represents the new length of array.
  • Now print the new array of length 'p'.

Method:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in); 
        System.out.print("Enter the number of elements in the array: "); 
        int num = sc.nextInt(); 
        int arr[] = new int[num]; 
        System.out.print("Enter the elements: "); 
        for (int i = 0; i < num; i++) 
        { 
        arr[i] = sc.nextInt(); 
        }
        
        // Displaying the array
        System.out.print("Original array : ");
        //printing the array
        for(int i = 0; i < arr.length; i++)
            System.out.print(arr[i]+" ");
        System.out.println();

        //calling the deleteNegative() method
        //to check negative elements in array and delete that
        int k=deleteNegative(arr);
        System.out.print("After deleting negative elements from array : ");
        //printing the array
        for(int i = 0; i < k; i++)
            System.out.print(arr[i]+" ");
        System.out.println();
    }
    
     //deleteNegative() method
    public static int deleteNegative(int[] arr) 
    {
    int p = 0;
    //iterating the array
    for(int i = 0; i <arr.length; i++) 
    {
        //if element is positive
        //then only we are storing that in arr[p], in same input array
        //which means we did not store negative elements 
        //so at last in the array all positive numbers will be available and negative numbers deleted
       if(arr[i] > 0) 
       {
           arr[p++] = arr[i];
       }
    }
    // input array holding the output data
    // 'p' is the final length of new array
    return p;
    }

}

Output:

Enter the number of elements in the array: 7
Enter the elements: 10 -20 -30 40 50 -60 70
Original array : 10 -20 -30 40 50 -60 70 
After deleting negative elements from array : 10 40 50 70

Method-2: Java Program to Delete All the Negative Elements from the Array By Using an Extra Array

Approach:

  • Approach is completely same as like above logic the only difference is that here we are storing the result in an extra array rather than the same input array.

Method:

import java.util.*;
public class Main
{    
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in); 
        System.out.print("Enter the number of elements in the array: "); 
        int num = sc.nextInt(); 
        int arr[] = new int[num]; 
        System.out.print("Enter the elements: "); 
        for (int i = 0; i < num; i++) 
        { 
        arr[i] = sc.nextInt(); 
        }
        
        // Displaying the array
        System.out.print("Original array : ");
        //printing the array
        for(int i = 0; i < arr.length; i++)
            System.out.print(arr[i]+" ");
        System.out.println();

        //calling the deleteNegative() method
        //to check negative elements in array and delete that
        deleteNegative(arr);
    }
    
    //deleteNegative() method
    public static void deleteNegative(int[] arr) 
    {
    int[] outputArray = new int[arr.length];
    int p = 0;
    //iterating the array
    for(int i = 0; i < arr.length; i++) 
    {
        //if element is positive
        //then only we are storing that in outputArray[p]
        //which means we did not store negative elements 
        //so at last in the array all positive numbers will be available and negative numbers deleted
       if(arr[i] > 0) 
       {
           outputArray[p++] = arr[i];
       }
    }
    System.out.print("After deleting negative elements from array : ");
    //printing the array
    for(int i = 0; i < p; i++)
        System.out.print(outputArray[i]+" ");
    System.out.println();
   }

}

Output:

Enter the number of elements in the array: 6
Enter the elements: 10 20 -30 -40 50 -60
Original array : 10 20 -30 -40 50 -60 
After deleting negative elements from array : 10 20 50

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

Related Java Programs: