I'm going through some practice problems, and I saw this code:
#include <stdio.h>
#include <string.h>
int main(void) {
char* s = "357";
int sum = 0;
int i = 0;
for (i = 0; i < strlen(s); i++) {
sum += s[i] - 48;
}
printf("Sum is %d", sum);
return 0;
}
Can someone explain what the code does, especially the subtraction with 48 part?
Finding the sum of the numbers in the string s.
The
sum += s[i] - 48;
converts ASCII characters to their numeric values.its adding up 3 + 5 + 7, and then printing
The
-48
part is that it is subtracting the character 0, that is, the ascii value for 0.So what it does is
As you can see, in C, '0' (character zero) is different from 0 (number 0). They have different values (amongst other things)
The code basically sums the digits of a number represented as a string. It makes two important assumptions to work properly:
'0'..'9'
rangeIn ASCII,
'0' == 48
,'1' == 49
, and so on. Thus,'0' - 48 == 0
,'1' - 48 == 1
, and so on. That is, subtracting by 48 translates thechar
values'0'..'9'
to theint
values0..9
.Thus, precisely because
'0' == 48
, the code will also work with:The intention is perhaps slightly more clear in this version.
You can of course do the "reverse" mapping by addition, e.g.
5 + '0' == '5'
. Similarly, if you have achar
containing a letter in'A'..'Z'
range, you can "subtract"'A'
from it to get the index of that letter in the0..25
range.See also
Related questions
'0'
and48
!On alternative encodings
As mentioned, the original
- 48
code assumes that the character encoding used is ASCII.- '0'
not only improves readability, but also waives the ASCII assumption, and will work with any encoding, as specified by the C language which stipulates that digit characters must be encoded sequentially in a contiguous block.On the other hand, no such stipulation is made about letters. Thus, in the rare situation where you're using EBCDIC encoding, for example, mapping
'A'..'Z'
to0..25
is no longer as simple as subtracting'A'
, due to the fact that letters are NOT encoded sequentially in a contiguous block in EBCDIC.Some programming languages simplify matters by mandating one particular encoding is used to represent the source code (e.g. Java uses Unicode: JLS §3.1)
See also
Related questions
I suggest writing a test program to see what the values of s[] display. You might also print out all the values for each entry in "0123456789".
I think you'll quickly realize what it's doing, although this code is relying on ASCII encoding.
Have fun!