Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert an int to ASCII character in C/C++
In C, every character like 'A', 'b', '3', or '@' is stored as a number called its ASCII value. For example, 'A' is 65, and 'a' is 97. Given an integer like 97, we can convert it to its corresponding ASCII character which is 'a'.
Syntax
char character = (char)asciiValue;
We can convert an integer to an ASCII character using simple methods. Here are two common approaches −
- Typecasting to Convert int to ASCII Character
- Using printf for int to ASCII Conversion
Method 1: Typecasting to Convert int to ASCII Character
In this method, we convert an integer directly to a character using typecasting. Since ASCII characters are stored as numbers inside the computer, casting an int to char gives us the character that matches the ASCII value.
#include <stdio.h>
int main() {
int asciiValue = 65;
char character = (char)asciiValue;
printf("The ASCII character for %d is '%c'\n", asciiValue, character);
return 0;
}
The ASCII character for 65 is 'A'
Method 2: Using printf for int to ASCII Conversion
In this approach, we directly pass the integer to the printf function using the %c format specifier to display the corresponding ASCII character.
#include <stdio.h>
int main() {
int asciiValue = 97;
printf("The ASCII character for %d is '%c'\n", asciiValue, asciiValue);
return 0;
}
The ASCII character for 97 is 'a'
Example with Multiple Values
Here's a complete example showing conversion of multiple ASCII values ?
#include <stdio.h>
int main() {
int values[] = {65, 97, 57, 33, 36};
int size = 5;
printf("ASCII Value to Character Conversion:\n");
for (int i = 0; i < size; i++) {
printf("%d -> '%c'\n", values[i], (char)values[i]);
}
return 0;
}
ASCII Value to Character Conversion: 65 -> 'A' 97 -> 'a' 57 -> '9' 33 -> '!' 36 -> '$'
Key Points
- Valid ASCII values range from 0 to 127 for standard ASCII characters.
- Typecasting
(char)asciiValueis the most direct method. - Using
%cformat specifier with printf automatically converts int to char. - Both methods have O(1) time and space complexity.
Conclusion
Converting an integer to ASCII character in C is straightforward using typecasting or printf's %c format specifier. Both methods work efficiently for any valid ASCII value from 0 to 127.
