Replacing each Negative Integer with 0 in an Array
This lesson will help you replace negative values in an array with 0 using recursion.
Replacing Negative Values with Zero
Given an array, replace negative values in an array with 0.
The following illustration clears the concept:
Implement 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.
Press + to interact
#include <iostream>using namespace std;//Recursive functionvoid replaceNegativeValues(int array[], int size, int currentIndex) {if (currentIndex >= size) {return;}// Replace negative numbers with 0if (array[currentIndex] < 0) {array[currentIndex] = 0;}// Recursively call the function for the next indexreplaceNegativeValues(array, size, currentIndex + 1);}//Driver Functionint main(){int array[7]={2,-3,4,-1,-7,8,3};//define an arrayint size=7; //define the size of arraycout<<"Replace negative values with 0:\n";replaceNegativeValues(array,size,0); //call the recursive functionfor (int i=0;i<7;i++)//print the arraycout<<array[i]<<' ';return 0;}
Understanding the Code
A recursive code can be broken down into two parts ...