How to use atoi In C Language

If the execution is successful, the atoi() method returns the converted integer value. If the given string cannot be converted to an integer, it will return 0. Below is the C program to convert char to int using atoi()

Example:

C




// C program to demonstrate conversion of
// char to int using atoi()
#include <stdio.h>
#include <stdlib.h>
// Driver code
int main()
{
    const char* str = "136";
 
    int y = atoi(str);
    printf("\nThe integer value of y is %d", y);
    return 0;
}


Output

The integer value of y is 136

4. Converting char to int by adding 0 

C




#include <stdio.h>
   
// Driver code
int main()
{
    char ch = 'g';
    int N = (int)(ch)+0;
    printf("%d", N);
    return 0;
}


Output

103

Method: ASCII value subtraction

  1. Read the input character from the user.
  2. Subtract the ASCII value of ‘0’ from the input character to get the equivalent integer value.
  3. Repeat step 2 for all the characters in the input string.
  4. Add up all the individual integer values to get the final integer value.

C




#include <stdio.h>
 
int main() {
    char input[100] = "12345";
    int i, result = 0;
 
    for (i = 0; input[i] != '\0'; i++) {
        result = result * 10 + (input[i] - '0');
    }
 
    printf("The integer value is: %d\n", result);
 
    return 0;
}


Output

The integer value is: 12345

The time complexity of this program is O(n), where n is the number of digits in the input string.

The auxiliary space used by this program is O(1)



C Program For Char to Int Conversion

There are 3 ways to convert the char to int in C language as follows:

  1. Using Typecasting
  2. Using sscanf()
  3. Using atoi()

Let’s discuss each of these methods in detail.

Similar Reads

1. Using Typecasting

Method 1:...

2. Using sscanf

...

3. Using atoi

...

Contact Us