Firstly, bits/*
are not standard headers, you shouldn't be using them otherwise your code may not compile with compilers like MSVC. Refer this.
Now let's come to your query : str[i] - '0'
is simply a way to convert char
to respective int
, i.e. '0'
to 0
. You can find more discussion on this thread.
What does your code do?
It just keeps on extracting chars from your string (in loop), converting it to int
and adding to num
after multiplying it by 10
. This is basically converting a part of string, say, "97"
to an integer 97
.
When num
comes in range from 32
(' '
) to 122
('Z'
) (both inclusive), it cast them to char
and prints it.
Explanation of Sample Output:
Your code prints a A
to console. You will get this result if you can figure out the substrings. Here consider these three - "97" "32" "65"
. Then "97"
will be converted to 97
(as int
), then will be cast to char
and end up being 'a'
('a'
has ASCII value of 97
). Similarly "32"
, will be a space ' '
, and "65"
will be 'A'
.
These substrings didn't come here by magic. Let me explain one for you :
You have str = "973265"
, num = 0
, then the loop begins :
i = 0
-> str[i] = '9'
-> str[i] - '0' = 9
-> num = 0*10 + 9 = 9
-> is num in range [32, 122]
? false
-> go to next iteration.
i = 1
-> str[i] = '7'
-> str[i] - '7' = 7
-> num = 9*10 + 7 = 97
-> is num in range [32, 122]
? true
-> ch = (char)num = (char)97 = 'A'
-> print ch
, i.e. 'A'
-> num = 0
-> go to next iteration.
Pro Tip: Use your debugger, set breakpoints, watch variables and step through your code for better understanding.
Note that: When I wrote ____ - I meant ____ like this ____.
- "convert" -- conversion --
'0' <-> 0
or "12" <-> 12
- "cast" -- casting --
'0' <-> 48
(assuming your compiler is using ASCII).