Search⌘ K

Replacing each Negative Integer with a 0 in an Array

Explore how to apply recursion to process arrays in Java by replacing each negative integer with zero. Learn to define base and recursive cases and trace the recursion flow to solve array modification problems efficiently.

Replacing Negative Values with Zero

When given an array, replace all negative values in that array with 0.

The following illustration clears this concept:

Implementing the Code

The following code explains how to replace each negative value in the array with 0.

Experiment with the code by changing the values of array to see how it works.

Recursive
Iterative
import java.io.*;
class ArrayClass {
private static void replaceNegativeValues(int[] a, int currentIndex) {
if (currentIndex == a.length)
return;
else {
if (a[currentIndex] < 0) {
a[currentIndex] = 0;
replaceNegativeValues(a, currentIndex+1);
}
else {
a[currentIndex] = a[currentIndex];
replaceNegativeValues(a, currentIndex+1);
}
}
}
public static void main(String[] args) {
System.out.println("Before: ");
int[] array = {2,-3,4,-1,-7,8,-2};
System.out.print("{ ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println("} ");
System.out.println("After: ");
replaceNegativeValues(array, 0);
System.out.print("{ ");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.print("} ");
}
}

Understanding the Code

The code snippet above can be broken down into two parts: The recursive method and the main where the ...