Login M Inbox M Boîte O Topic: O Report O Report O Report G Googl O Course b http:// O Portal O PE02 O Report 6 codec A Not secure | codecheck.it/files/2004190648cncpp3knq10xldpjmplgg02y4 Complete the following file: ZeroFirstDuplicate.java public class ZeroFirstDuplicate { public static void zeroFirst(int[] a) { // Given an array, whenever two consecutive elements // are equal, overwrite the first with a zero. // (You can assume the input array contains no zeros and // that the input array will not contain three or more // consecutive equal elements. See test cases.) 4 9. 10 Your code here... 11 12 13 14 15 } 16 public static void main(String[] args) { // Ignore the code in this method. // Your code will be tested somewhere else. int caseNum = 1; ZeroFirstDuplicateRun.run(caseNum); } 17 18 19 20 21 22 23 24 9:47 PM P Type here to search 99+ 4/20/2020
- The program initializes a user define array and passes it to the function zeroFirst.
- In zeroFirst the array is copied to another array for comparison purposes.
- First an if condition is used to check index is greater than 1. If it is greater than 1 then another condition comparing and equating previous 2 elements is checked. If they are equal then the first occurrence is changed to zero.
- The resultant array is printed.
import java.util.*;
public class ZeroFirstDuplicate {
public static void main (String[] args) {
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array: (max 100): ");
n = s.nextInt();
int a[] = new int[n];
System.out.print("Enter elements of array: \n");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
zeroFirst(a);
int caseNum = 1;
ZeroFirstDuplicate.run(caseNum);
s.close();
}
private static void run(int caseNum) {
// TODO Auto-generated method stub
}
public static void zeroFirst(int[] a) {
int b[] = a;
int i;
for(i = 0; i < a.length; i++)
{
if(i > 1)
{
if(a[i - 2] == b[i - 1])
{
a[i - 2] = 0;
i++;
}
}
}
for(i = 0; i < a.length; i++)
System.out.println(a[i]);
}
}
Step by step
Solved in 3 steps with 1 images