#include /** * ctoi(char) * Convert a digit character to the correspnding integer. */ int ctoi(char ch) { return ch - '0'; } // ctoi /** * atoi(str) * "Parse" a string to the underlying integer. */ int atoi (char a[]) { int i = 0; // Counter variable for string int result = 0; // What I've computed so far // For a two digit number, we can use // 10 * ctoi(a[0]) + ctoi(a[1]) // Generalize: // As long as characters remain, while (a[i] != '\0') { // multiply the current result by 10 // add the converted character result = result * 10 + ctoi (a[i]); // Move on to the next character i = i + 1; } // while // And we're done return result; } // atoi int main () { printf ("%d\n", atoi("5317")); printf ("%d\n", atoi("235")); printf ("%d\n", atoi("1")); printf ("%d\n", atoi("two")); return 0; } // main