spoj-LASTDIG2;conceptual problem

the link to code is 3IiNTw - Online C Compiler & Debugging Tool - Ideone.com .
I am not able to understand why we have to subtract 48 that is ‘0’ in step a=str[len-1]-‘0’. Without subtrcting i am getting wrong answer. please explain why is it so?

The buffer str contains the Ascii values of the characters - Ascii Table.

The character ‘0’ is represented by the ascii code 48, and the digits ‘0’…‘9’ appear consecutively in the Ascii Table. So, if you want to get the corresponding digit value of characters ‘0’, ‘1’, … ‘9’, you need to subtract the ascii value of ‘0’.

See this. If you are using the character for subtraction then, you need to mention -'0' thing, t get the offset i.e.

a-'0' 

this will return (97-48). Why this happens is because of the fact that char is one of C's numeric integer data types. That implies all characters are stored as numeric constants in the memory. Ask why we always do printf("%c",k) for printing any character? Because we want whatever is stored in memory with identifier as k, to be processed as character. Thus, simply the two types are convertible. But as we know, the perations can be applied on similar types, so we need to do

cout<<'a'-'0' ;
cout<<(int)('a')-48;

Both will return the same answer i.e. 49.

Hope it clears… :slight_smile:

How can u say that str contains ASCII value of characters??and is it containing ASCII value of each digit separately in different indices??

that’s how computers work. each byte of a string is the ascii value of the character.

thank u…I got it…here it means that our character is 0 but for arithmetic operations its ASCII value 48 is taken bcoz in these operations char are implicitly converted to int.I hope that I understood correcly…

Thank you…I got it…