...

/

Replacing each Negative Integer with 0 in an Array

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 function
void replaceNegativeValues(int array[], int size, int currentIndex) {
if (currentIndex >= size) {
return;
}
// Replace negative numbers with 0
if (array[currentIndex] < 0) {
array[currentIndex] = 0;
}
// Recursively call the function for the next index
replaceNegativeValues(array, size, currentIndex + 1);
}
//Driver Function
int main()
{
int array[7]={2,-3,4,-1,-7,8,3};//define an array
int size=7; //define the size of array
cout<<"Replace negative values with 0:\n";
replaceNegativeValues(array,size,0); //call the recursive function
for (int i=0;i<7;i++)//print the array
cout<<array[i]<<' ';
return 0;
}

Understanding the Code

A recursive code can be broken down into two parts ...