mardi 2 février 2021

Checking and replacing a duplicate in a single for loop

So I have set up my code to be this (note I have my user input for the array and display of the results in another function and a beginner)

int main( )
{
    using namespace std;

    int a[8];

    populateArray(a, 8);

    cout<<"The array is: ";
    displayArray(a, 8);
    cout<<"\nThis array becomes: "<<sameElement(a, 8);

int sameElement(int a[], int size)
{
    using namespace std;

    for(int i = 0; i < size; i ++)
        {
            if( a[i] == a[i +1])
            {
                a[i + 1] = 0;
                return i;
            }
            else
                {
                    return a[i];
                }
        }

}

Been trying to see if a user puts a duplicate number(that works fine and great). That same array that the user input I want to replace that duplicate to a zero. Sadly I get either a single 0, 1, or 2 and it replaces the entire array. not sure how to return it back to my main as it also says that I have nothing returning from my function despite invoking it in my function and trying to find the right way to return my function. I have declared my function on top and they both match with the parameter as well. So still don't see why I keep getting an issue of returning my function to main?

Example:

The array: 1 2 2 3 4 5 5 7 Array becomes 1 0 0 3 4 0 0 7

Aucun commentaire:

Enregistrer un commentaire