Write your own C program to implement the atoi() function

Write your own C program to implement the atoi() function

The C library function int atoi(const char *str) converts the string argument str to an integer (type int). This problem is about to write own atoi( ) function which has same argument parameter and return type which also checks for null string and string contain any character.

Declaration

int atoi(const char *str);

Algorithm

Algorithm is pretty simple, we know that char type is hold the ASCII value of any number or character so we just minus the ASCII value of zero from the given string’s individual character and manage it by multiply by 10 and adding sequentially. See below code for more clarification 

 

 

Suggested Reading

  1. How can I convert numbers to strings (itoa() function)?
  2. Write your own printf() function in c
  3. Write your own trim() or squeeze() function to remove the spaces from a string
  • Triv1um

    “if( str[i] = ‘9’)”
    There is a error with the char check. It wont allow 0’s or 9’s.
    Just remove the = from both less than and more than operators.