Home > Blockchain >  Separating the 0s and Positive Numbers in two different arrays
Separating the 0s and Positive Numbers in two different arrays

Time:03-06

This is the code I have written, My objective is to segregate the 0s and non 0s without changing the order of the non 0s

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int x = sc.nextInt();

        int[] arx;
        arx = new int[x];

        int[] ary;
        ary = new int[x];

        for (int i = 0; i < x; i  ) {
            int q = sc.nextInt();
            if (q != 0) {
                arx[i] = q;
            } else if (q == 0) {
                ary[i] = q;
            }
        }
        for (int j = 0; j < arx.length; j  ) {
            System.out.print(arx[j]   " ");
        }

        for (int j = 0; j < ary.length; j  ) {
            System.out.print(ary[j]   " ");
        }
    }

}

Sample i/p:

5
0 1 0 3 12

Sample o/p:

1 3 12 0 0

What I am getting: o/p:

0 1 0 3 12 0 0 0 0 0 

CodePudding user response:

You should maintain separate index counters for the two arrays:

int x = sc.nextInt();
int ix = 0;
int iy = 0;

int[] arx;
arx = new int[x];

int[] ary;
ary = new int[x];

for (int i=0; i < x; i  ) {
    int q = sc.nextInt();
    if (q != 0) {
        arx[ix  ] = q;           
    }
    else if (q == 0) {
        ary[iy  ] = q;
    }
}

for (int i=0; i < ix; i  ) {
    System.out.print(arx[i]   " ");
}

for (int i=0; i < iy; i  ) {
    System.out.print(ary[i]   " ");
}

For your inputs the above generated the following output:

1 3 12 0 0

CodePudding user response:

Since array with arx is filled with zeroes , you can only use one array to add non zero values.

 {
    Scanner sc = new Scanner (System.in);

    int x = sc.nextInt ();

    int[] arx;
      arx = new int[x];

    int ind = 0;
    for (int i = 0; i < x; i  ) {
        int q = sc.nextInt ();
        if (q != 0){
            arx[ind  ] = q;
          }
      }
    for (int j = 0; j < arx.length; j  ){
        System.out.print (arx[j]   " ");
      }
  }
  • Related