Replacing each Negative Integer with a 0 in an Array
This lesson will teach you how to replace negative values in an array with 0 using recursion.
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.
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 ...