dimanche 4 juillet 2021

How to check if all array items are consecutive and finish at value 9

I have an array of user defined length 0<n<10 and I want to check if arr[i]-arr[i-1] == 1 for all pairs i know I can iterate over them but I was wondering if there is an easier way that I could put inside of the if .

Edit: I just realised while tinkering with this that I don't know how to do it even iterating I need last item to be 9!

what I have:

bool is_consecutive(int arr[], int leng)
{
    int i = 0;
    if (leng > 1)
    {
        while (i < n)
        {
            if (arr[i+1]-arr[i] != 1)
                return false;
            else if ( i == leng - 1 && arr[i] == 9)
                return true
        }
    }
    else if (arr[leng-1] == 9)
        return true;
    else
        return false;
}

Aucun commentaire:

Enregistrer un commentaire