0
0
CProgramBeginner · 2 min read

C Program to Convert Char to Int with Example

In C, you can convert a digit character to an integer by subtracting the character '0' like this: int num = ch - '0'; where ch is the char digit.
📋

Examples

Input'5'
Output5
Input'0'
Output0
Input'9'
Output9
🧠

How to Think About It

To convert a character representing a digit to its integer value, think of the characters as numbers in the computer's code table. The digits '0' to '9' are in order, so subtracting the character '0' from any digit character gives the actual number it represents.
📐

Algorithm

1
Get the input character representing a digit.
2
Subtract the character '0' from the input character.
3
Store the result as an integer.
4
Print or return the integer value.
💻

Code

c
#include <stdio.h>

int main() {
    char ch = '7';
    int num = ch - '0';
    printf("The integer value is: %d\n", num);
    return 0;
}
Output
The integer value is: 7
🔍

Dry Run

Let's trace the example where ch = '7' through the code.

1

Input character

ch = '7'

2

Subtract '0'

num = '7' - '0' = 55 - 48 = 7 (ASCII values)

3

Print result

Output: The integer value is: 7

ch'0'num
'7''0'7
💡

Why This Works

Step 1: Characters have numeric codes

Each character like '0' or '7' has a number code in the computer (ASCII).

Step 2: Subtracting '0' gives digit value

Since '0' to '9' are in order, subtracting '0' from a digit character gives its integer value.

Step 3: Store and use as integer

The result is stored as an int and can be used in calculations or printed.

🔄

Alternative Approaches

Using sscanf
c
#include <stdio.h>

int main() {
    char ch = '4';
    int num;
    sscanf(&ch, "%1d", &num);
    printf("The integer value is: %d\n", num);
    return 0;
}
This method reads the character as a digit using sscanf but is less direct and slightly slower.
Using atoi with string
c
#include <stdio.h>
#include <stdlib.h>

int main() {
    char str[2] = {'3', '\0'};
    int num = atoi(str);
    printf("The integer value is: %d\n", num);
    return 0;
}
Converts a string to int but requires creating a string, which is more complex for a single char.

Complexity: O(1) time, O(1) space

Time Complexity

The operation is a simple subtraction and assignment, so it runs in constant time.

Space Complexity

Only a few variables are used, so space is constant.

Which Approach is Fastest?

Subtracting '0' is the fastest and simplest method compared to sscanf or atoi.

ApproachTimeSpaceBest For
Subtract '0'O(1)O(1)Simple and fast conversion
sscanfO(1)O(1)Parsing formatted input, less efficient
atoi with stringO(1)O(1)Converting strings, more complex for single char
💡
Always subtract '0' from a digit character to get its integer value in C.
⚠️
Trying to cast the char directly to int without subtracting '0' gives the ASCII code, not the digit value.