Ahmed Mahmoud
Ahmed Mahmoud

Reputation: 21

C++ code error assignment

I have a question on my assignment that tells me

If a certain character is a number , it must be transformed to another character whose value equals the remainder of original number n division by 4 (n%4). For example if the user inputs “987654” , the output ( after taking the remainder and reversing the array) should be : “012301” .

The code i've written works well very much except for this part i want to take the remainder in my function but it doesn't seem to work at all any suggestions ?

void function(char x[], int size)
{

        **if (x[i] >= '0' && x[i] <= '9')
        {
            x[i]=x[i] % 4;
        }**
        cout << x[i];
    }
    cout<<endl;
}


}

Upvotes: 0

Views: 73

Answers (1)

ilim
ilim

Reputation: 4547

Your array x contains characters but in the section you highlighted, the transformation relies on finding the integer value n represented by that digit character x[i].

Luckily, since the ASCII value representing '0' character is divisible by 4, even if you do not subtract the value of '0' from x[i], the outcome of the modulus operation is not affected. Nonetheless, after finding the modulo 4 of n, you end up with an integer value in the range [0, 4). To reflect that back to the string, as a character, you need to add back the integer value of '0' to it.

Below is a code sample demonstrating what I mentioned above.

if (x[i] >= '0' && x[i] <= '9')
{
    int n = (x[i] - '0');
    x[i] = (n % 4) + '0';
}

Upvotes: 1

Related Questions