0% found this document useful (0 votes)
3 views

assignment_star2

The document contains two Java programs that shift all zeros in an array to the end while maintaining the order of non-zero elements. The first approach counts non-zero elements and fills the array accordingly, while the second approach uses a temporary array to achieve the same result. Both programs prompt the user for input and display the modified array.

Uploaded by

Akash Padir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

assignment_star2

The document contains two Java programs that shift all zeros in an array to the end while maintaining the order of non-zero elements. The first approach counts non-zero elements and fills the array accordingly, while the second approach uses a temporary array to achieve the same result. Both programs prompt the user for input and display the modified array.

Uploaded by

Akash Padir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

import java.util.

Scanner;

public class newShiftZero {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = 0;
System.out.println("Enter the number of elements");
int n = sc.nextInt();
System.out.println("Enter the array");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}

for (int num : arr) {


if (num != 0) {
count++;
}
}

//zero placing
for (int i = 0; i < arr.length - count; i++) {
arr[i] = 0;
}

// non zero
for (int i = arr.length - count, j = 0; j < arr.length; j++) {
if (arr[j] != 0) {
arr[i++] = arr[j];
}
}

for (int i = 0; i < n; i++) {


System.out.print(arr[i] + " ");
}
}

APPROACH 2

import java.util.*;
public class zeoShift {
public static void main(String args[]){
Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of elements");


int n = sc.nextInt();
System.out.println("Enter the array");
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}

int[] temp = new int[n];


int k = n - 1;
for (int i = n - 1; i >= 0; i--) {
if (arr[i] != 0) {
temp[k--] = arr[i];
}
}
for (int i = 0; i <= k; i++) {
temp[i] = 0;
}
for (int i = 0; i < n; i++) {
arr[i] = temp[i];
}

for (int i = 0; i < arr.length; i++) {


System.out.print(arr[i] + " ");
}
System.out.println();
}
}

You might also like