Write a C program to convert the given numeric character to integer.
Example:
Input: '3'
Output: 3
Explanation: The character '3' is converted to the integer 3.Input: '9'
Output: 9
Explanation: The character '9' is converted to the integer 9.
Different Methods to Convert the char to int in C
There are 3 main methods to convert the char to int in C language as follows:
Table of Content
Let's discuss each of these methods in detail.
1. Using ASCII Values
Each character in C has an ASCII value, a unique numerical representation. For numeric characters like '0', '1', etc., the ASCII value starts from 48 for '0' and increases sequentially. To convert a char to its integer equivalent, subtract the ASCII value of '0' from the character.
C Program to Convert char to int Using ASCII Values
// C program to convert the given char to int using
// ASCII values
#include <stdio.h>
int main() {
// Define a numeric character variable
char ch = '7';
// Convert the character to integer by subtracting
// ASCII value of '0'
int N = ch - '0';
// Print the result
printf("The integer value of character '%c' is %d\n", ch, N);
return 0;
}
Output
The integer value of character '7' is 7
Time Complexity: O(1)
Space Complexity: O(1)
2. Using sscanf() Function
The sscanf() function can be used to read formatted input from a string. It can convert a character to an integer by treating the character as a string and reading it using the format specifier for an integer (%d).
C Program to Convert char to int Using sscanf() Function
// C program to demonstrate conversion of
// char to int using sscanf()
#include <stdio.h>
int main() {
// Define a character variable
char ch = '8';
// Declare an integer variable to store the converted value
int N;
// Use sscanf to convert the character to an integer
sscanf(&ch, "%d", &N);
printf("The integer value of character '%c' is %d\n", ch, N);
return 0;
}
Output
103
Time Complexity: O(1)
Space Complexity: O(1)
3. Using atoi() Function
The atoi() function from the C Standard Library <stdlib.h> can convert a string of digits into an integer. Although atoi() is designed for strings, it can be used with single-character strings.
C Program to Convert char to int Using atoi()
// C program to demonstrate conversion of char to int
// using atoi()
#include <stdio.h>
#include <stdlib.h>
int main() {
// Define a character variable
char ch = '5';
// Convert the character to a string and then use
// atoi() to convert it to an integer
int N = atoi(&ch);
// Print the result
printf("The integer value of character '%c' is %d\n", ch, N);
return 0;
}
Output
The integer value of character '5' is 5
Time Complexity: O(1)
Space Complexity: O(1)