Spread the love

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 

 

#include <stdio.h>

int Atoi(char *str)
{
    if (*str == '\0')
       return 0;
 
    int res = 0;		// Initialize result
    int sign = 1;		// Initialize sign as positive
    int i = 0;			// Initialize index of first digit
 
     if (str[0] == '-')
    {
        sign = -1;
        i++;  			// Also update index of first digit
    }
 
    for (; str[i] != '\0'; ++i)
    {
        if ( str[i] <= '0' || str[i] >= '9')	// If string contain character it will terminate
            return 0; 
            
        res = res*10 + str[i] - '0';
    }
 
    return sign*res;
}
 
int main()
{
    char str[] = "1234";
    
    printf("%d ", Atoi(str));
    
    return 0;
}

 

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