C Program To Write Your Own atoi()
Last Updated :
27 Feb, 2023
The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer.
Syntax:
int atoi(const char strn)
Parameters: The function accepts one parameter strn which refers to the string argument that is needed to be converted into its integer equivalent.
Return Value: If strn is a valid input, then the function returns the equivalent integer number for the passed string number. If no valid conversion takes place, then the function returns zero.
Example:
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int val;
char strn1[] = "12546";
val = atoi(strn1);
printf("String value = %s
", strn1);
printf("Integer value = %d
", val);
char strn2[] = "GeeksforGeeks";
val = atoi(strn2);
printf("String value = %s
", strn2);
printf("Integer value = %d
", val);
return (0);
}
OutputString value = 12546
Integer value = 12546
String value = GeeksforGeeks
Integer value = 0
Time Complexity: O(1)
Auxiliary Space: O(1)
Now let's understand various ways in which one can create their own atoi() function supported by various conditions:
Approach 1: Following is a simple implementation of conversion without considering any special case.
- Initialize the result as 0.
- Start from the first character and update result for every character.
- For every character update the answer as result = result * 10 + (s[i] - '0')
C
// Program to implement atoi() in C
#include <stdio.h>
// A simple atoi() function
int myAtoi(char* str)
{
// Initialize result
int res = 0;
// Iterate through all characters
// of input string and update result
// take ASCII character of corresponding digit and
// subtract the code from '0' to get numerical
// value and multiply res by 10 to shuffle
// digits left to update running total
for (int i = 0; str[i] != ''; ++i)
res = res * 10 + str[i] - '0';
// return result.
return res;
}
// Driver Code
int main()
{
char str[] = "89789";
// Function call
int val = myAtoi(str);
printf("%d ", val);
return 0;
}
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach 2: This implementation handles the negative numbers. If the first character is '-' then store the sign as negative and then convert the rest of the string to number using the previous approach while multiplying sign with it.
C
// A C program for
// implementation of atoi
#include <stdio.h>
// A simple atoi() function
int myAtoi(char* str)
{
// Initialize result
int res = 0;
// Initialize sign as positive
int sign = 1;
// Initialize index of first digit
int i = 0;
// If number is negative,
// then update sign
if (str[0] == '-') {
sign = -1;
// Also update index of first digit
i++;
}
// Iterate through all digits
// and update the result
for (; str[i] != ''; ++i)
res = res * 10 + str[i] - '0';
// Return result with sign
return sign * res;
}
// Driver code
int main()
{
char str[] = "-123";
// Function call
int val = myAtoi(str);
printf("%d ", val);
return 0;
}
Time Complexity: O(N)
Auxiliary Space: O(1)
Approach 3: This implementation handles various type of errors. If str is NULL or str contains non-numeric characters then return 0 as the number is not valid.
Approach 4: Four corner cases needs to be handled:
- Discards all leading whitespaces
- Sign of the number
- Overflow
- Invalid input
To remove the leading whitespaces run a loop until a character of the digit is reached. If the number is greater than or equal to INT_MAX/10. Then return INT_MAX if the sign is positive and return INT_MIN if the sign is negative. The other cases are handled in previous approaches.
Dry Run:

Below is the implementation of the above approach:
C
// A simple C++ program for
// implementation of atoi
#include <stdio.h>
#include <limits.h>
int myAtoi(const char* str)
{
int sign = 1, base = 0, i = 0;
// if whitespaces then ignore.
while (str[i] == ' ')
{
i++;
}
// sign of number
if (str[i] == '-' || str[i] == '+')
{
sign = 1 - 2 * (str[i++] == '-');
}
// checking for valid input
while (str[i] >= '0' && str[i] <= '9')
{
// handling overflow test case
if (base > INT_MAX / 10
|| (base == INT_MAX / 10
&& str[i] - '0' > 7))
{
if (sign == 1)
return INT_MAX;
else
return INT_MIN;
}
base = 10 * base + (str[i++] - '0');
}
return base * sign;
}
// Driver Code
int main()
{
char str[] = " -123";
// Functional Code
int val = myAtoi(str);
printf("%d ", val);
return 0;
}
// This code is contributed by Yogesh shukla.
Complexity Analysis for all the above Approaches:
- Time Complexity: O(n).
Only one traversal of string is needed. - Space Complexity: O(1).
As no extra space is required.
Recursive program for atoi().
Exercise:
Write your won atof() that takes a string (which represents an floating point value) as an argument and returns its value as double.
Please refer complete article on Write your own atoi() for more details!
Similar Reads
How to Write a Command Line Program in C?
In C, we can provide arguments to a program while running it from the command line interface. These arguments are called command-line arguments. In this article, we will learn how to write a command line program in C. How to Write a Command Line Program in C? Command line arguments are passed to the
2 min read
C Program To Print Your Own Name
Printing your own name means displaying your name on the computer screen. In this article, we will learn how to print your own name using a C program.ExamplesInput: name = "Rahul"Output: RahulExplanation: The program prints "Rahul" to the screen.Input: name = "Vikas"Output: VikasExplanation: The pro
3 min read
C Program To Print Triangle
Here, we will see how to print a triangle using the C program Input: 5 Output: * * * * * * * * * * * * * * * Approach: The approach is very simple. We just execute a nested loop, and only print characters when the inner loop is executed after that just change the line. Example: C // C program to pri
1 min read
Your First C Program
Like in most of the programming languages, program to write the text "Hello, World!" is treated as the first program to learn in C. This step-by-step guide shows you how to create and run your first C program.Table of ContentSetting Up Your EnvironmentCreating a Source Code FileNavigating to the Sou
4 min read
How to Take Operator as Input in C?
In C, an operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. We may need to take operator as an input in some cases. In this article, we will learn how to take an operator as input in C. Get Input Operator in CTo take an operator as input in C, we
2 min read
C Hello World Program
The âHello Worldâ program is the first step towards learning any programming language. It is also one of the simplest programs that is used to introduce aspiring programmers to the programming language. It typically outputs the text "Hello, World!" to the console screen.C Program to Print "Hello Wor
1 min read
String C/C++ Programs
C program to swap two StringsC Program to Sort an array of names or stringsC Program to Check if a Given String is PalindromeC/C++ Program for Return maximum occurring character in the input stringC/C++ Program for Remove all duplicates from the input string.C/C++ Program for Print all the duplicate
3 min read
How to Write a Struct to a Binary File in C?
C file handling allows users to store the data from a C program to a file in either the text or the binary format. In this article, we will learn how to write a struct to a binary file in C. Writing Structure into a Binary File in CTo write a struct to a binary file, we can use the fwrite() function
2 min read
How to Reverse a String in C?
In C, a string is a sequence of characters terminated by a null character (\0). Reversing a string means changing the order of the characters such that the characters at the end of the string come at the start and vice versa. In this article, we will learn how to reverse a string in C. Example: Inpu
2 min read
C Program to Make a Simple Calculator
A simple calculator is a program that can perform addition, subtraction, multiplication, and division of two numbers provided as input. In this article, we will learn to create a simple calculator program in C.ExampleInput: a = 10, b = 5, op = +Output: 15.00Explanation: Chosen operation is addition,
3 min read