# plz explain a small function

• 11-11-2004
samirself
plz explain a small function
//atoi: converts s to integer

int atoi(char s[])
{
int i,n;

n=0;

for(i=0; s[i]>='0' && s[i]<='9'; i++)

n=10*n + (s[i] - '0');

return n;
}

how the above func. works!

thanx
• 11-11-2004
DavT
You've been told before... use code tags.
This has to be your homework. Make an effort.
• 11-11-2004
ROCKaMIC
Why not use the atoi() function included in stdlib?? anyways..
i'm not even sure if the above function works.

but you could always play knowing that the ASCII code 48 is 0. substract 48 to every ASCII code that represents a number and knowing how many spaces to the left you could multiply by ten.

EDIT: lapsus mentis.. sorry lol i just explained what it did without really looking at the function, i just thought it didn't work because of the parameter, i would write

Code:

`atoi(char *s)`
• 11-11-2004
Dave_Sinkula
Debugging with printf:
Code:

```#include <stdio.h> int atoi(char s[]) {   int i, n = 0;   for ( i=0; s[i]>='0' && s[i]<='9'; i++ )   {       printf("10 * n = 10 * %4d = %5d, ", n, 10 * n);       printf("s[%d] - '0' = '%c' - '0' = %d - %d = %d, ",                 i,        s[i],      s[i], '0', s[i] - '0');       n = 10 * n + (s[i] - '0');       printf("n = %d\n", n);   }   return n; } int main ( void ) {   int result = atoi("12345");   printf("result = %d\n", result);   return 0; } /* my output 10 * n = 10 *    0 =    0, s[0] - '0' = '1' - '0' = 49 - 48 = 1, n = 1 10 * n = 10 *    1 =    10, s[1] - '0' = '2' - '0' = 50 - 48 = 2, n = 12 10 * n = 10 *  12 =  120, s[2] - '0' = '3' - '0' = 51 - 48 = 3, n = 123 10 * n = 10 *  123 =  1230, s[3] - '0' = '4' - '0' = 52 - 48 = 4, n = 1234 10 * n = 10 * 1234 = 12340, s[4] - '0' = '5' - '0' = 53 - 48 = 5, n = 12345 result = 12345 */```
• 11-11-2004
samirself
thanx a lot mate!
code tags means complete code which can be run