Suppose your s contains '1','2','3'. Before the loop, n=0. At i=0, s[i]-'0' is 1, so n=1. At i=1, s[i]-'0'=2, 10*n=10, so n will become 12. In the next iteration, n=12*10+3=123
Maybe, I am not following what the atoi function is supposed to do. I thought it gives the integer equivalent of an ascii character. So when we have a character '3', shouldn't it return 51 and not 123? http://www.asciitable.com/
atoi takes the string representation of a number and converts it to that number.
So if you call atoi on the string "123", it will return the int value 123.
If you want to convert a character to its ASCII value, you just need to cast it to an int (or otherwise): static_cast<int>('3') // Gives you 51 .
I see, for each iteration, we increase by power of 10, since we are using the decimal system, which is base-10. So first iteration is one's place. Second iteration is ten's place. Third iteration is in hundred's place. And so forth.